js实现mailto
使用JavaScript实现mailto链接
在HTML中创建mailto链接可以直接通过<a>标签实现,但通过JavaScript可以动态生成或修改mailto链接,提供更灵活的交互方式。
基本语法
window.location.href = 'mailto:email@example.com';
动态生成mailto链接
const email = 'user@example.com';
const subject = 'Hello';
const body = 'This is the email body content';
const mailtoLink = `mailto:${email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
window.location.href = mailtoLink;
添加多个收件人
在mailto链接中使用逗号分隔多个邮箱地址
const emails = ['user1@example.com', 'user2@example.com'].join(',');
window.location.href = `mailto:${emails}`;
包含抄送和密送
const mailtoLink = `mailto:primary@example.com?cc=cc@example.com&bcc=bcc@example.com`;
window.location.href = mailtoLink;
处理特殊字符
使用encodeURIComponent()确保主题和正文中的特殊字符正确编码
const subject = 'Test email with special characters: &, ?, =';
const encodedSubject = encodeURIComponent(subject);
window.location.href = `mailto:test@example.com?subject=${encodedSubject}`;
通过点击事件触发
<button id="emailButton">Send Email</button>
<script>
document.getElementById('emailButton').addEventListener('click', function() {
window.location.href = 'mailto:contact@example.com';
});
</script>
在新窗口打开mailto链接
window.open('mailto:test@example.com', '_blank');
注意事项
- 某些浏览器可能会阻止自动触发的mailto链接,特别是弹窗中的链接
- 移动设备上点击mailto链接通常会打开默认邮件应用
- 用户必须已配置邮件客户端才能正常使用此功能







