我想从JavaScript中调用mailto链接 - 也就是说,我想要一种方法,让我能够在用户的电脑上打开邮件客户端,就像他们点击普通的mailto链接一样。
我该如何做到这一点?
我想从JavaScript中调用mailto链接 - 也就是说,我想要一种方法,让我能够在用户的电脑上打开邮件客户端,就像他们点击普通的mailto链接一样。
我该如何做到这一点?
你可以在这里使用 window.location.href
,像这样:
window.location.href = "mailto:address@dmail.com";
window.location.href = 'mailto:address@dmail.com&subject=Hello there&body=This is the body';
。不要用 ?
和 &
,只需使用 &
。 - cssyphus您可以通过在页面上使用链接并使用 .click() 来避免上面讨论的空白页问题:
document.getElementById('mymailto').click();
...
<a href="mailto:...." id="mymailto" style="display:none"></a>
`,但新标签页仍然打开。 - Yoda对于我来说可行的解决方案,在chrome、IE和firefox中进行了测试,并与outlook一起使用:
window.location.href = 'mailto:address@dmail.com?subject=Hello there&body=This is the body';
%0d%0a
是邮件中 mailto 链接的换行符号。
%20
是应该使用的空格符号,但我也用普通空格成功了。
建议使用
window.open('mailto:address@mail.com?subject=sub&body=this is body')
如果我们使用window.location.href
,Chrome浏览器在网络选项卡中会出现错误,显示 Provisional headers are shown Upgrade-Insecure-Requests: 1
实际上,有可能避免空白页面。
我发现,你可以简单地将带有mailto链接的iframe插入到dom中。 这在当前的Firefox/Chrome和IE上都有效(即使IE也会显示一个短的确认对话框)。
使用jQuery,我得到了以下代码:
var initMailtoButton = function()
{
var iframe = $('<iframe id="mailtoFrame" src="mailto:name@domain.com" width="1" height="1" border="0" frameborder="0"></iframe>');
var button = $('#mailtoMessageSend');
if (button.length > 0) {
button.click(function(){
// create the iframe
$('body').append(iframe);
//remove the iframe, we don't need it any more
window.setTimeout(function(){
iframe.remove();
}, 500);
});
}
}
这是一个老问题,但我结合了几个 Stack Overflow 来编写这个函数:
//this.MailTo is an array of Email addresses
//this.MailSubject is a free text (unsafe) Subject text input
//this.MailBody is a free text (unsafe) Body input (textarea)
//SpawnMail will URL encode /n, ", and ', append an anchor element with the mailto, and click it to spawn the mail in the users default mail program
SpawnMail: function(){
$("#MyMailTo").remove();
var MailList="";
for(i in this.MailTo)
MailList+=this.MailTo[i]+";";
var NewSubject=this.MailSubject.replace(/\n/g, "%0d%0a");
NewSubject=NewSubject.replace(/"/g, "%22");
NewSubject=NewSubject.replace(/'/g, "%27");
var NewBody=this.MailBody.replace(/\n/g, "%0d%0a");
NewBody=NewBody.replace(/"/g, "%22");
NewBody=NewBody.replace(/'/g, "%27");
$("#mainNavBar").after("<a id='MyMailTo' style='display:none;' href='mailto:"+MailList+"?subject="+NewSubject+"&body="+NewBody+"'> </a>");
document.getElementById('MyMailTo').click();
}
<button onclick="window.open('mailto:KingRider<contato@sandroalvares.com.br>');">联系我</button>
- KingRider