js实现mailto
使用JavaScript实现mailto链接
在JavaScript中创建mailto链接可以通过动态生成HTML锚点标签或修改现有标签的属性来实现。mailto协议用于触发用户的默认邮件客户端,支持添加收件人、主题、正文等参数。
基本语法
mailto链接的基本语法如下:

<a href="mailto:recipient@example.com">Send Email</a>
动态创建mailto链接
通过JavaScript动态创建mailto链接:
const email = 'recipient@example.com';
const subject = 'Hello';
const body = 'This is the email body.';
const mailtoLink = `mailto:${email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
const link = document.createElement('a');
link.href = mailtoLink;
link.textContent = 'Send Email';
document.body.appendChild(link);
使用window.location.href
直接通过window.location.href触发邮件客户端:

window.location.href = 'mailto:recipient@example.com?subject=Hello&body=This%20is%20the%20email%20body.';
处理多个收件人
多个收件人可以用逗号分隔:
const recipients = 'recipient1@example.com,recipient2@example.com';
window.location.href = `mailto:${recipients}`;
添加CC和BCC
可以通过cc和bcc参数添加抄送和密送:
window.location.href = 'mailto:recipient@example.com?cc=cc@example.com&bcc=bcc@example.com';
注意事项
- 使用
encodeURIComponent对参数进行编码,确保特殊字符正确处理。 - 某些浏览器可能会阻止通过脚本触发的
mailto链接,需确保用户交互(如点击事件)触发。 - 移动设备上可能直接打开邮件应用,行为因操作系统和浏览器而异。






