在JavaScript中发送电子邮件通常涉及到使用后端服务,因为出于安全考虑,浏览器中的JavaScript无法直接发送电子邮件。以下是一些基础概念和相关信息:
以下是一个使用Node.js和Nodemailer库发送电子邮件的简单示例:
// 安装Nodemailer:npm install nodemailer
const nodemailer = require('nodemailer');
async function sendEmail(to, subject, text) {
// 创建一个SMTP传输对象
let transporter = nodemailer.createTransport({
host: 'smtp.example.com', // SMTP服务器地址
port: 587, // 端口
secure: false, // true for 465, false for other ports
auth: {
user: 'user@example.com', // 你的邮箱账号
pass: 'password' // 你的邮箱密码或应用专用密码
}
});
// 设置邮件选项
let mailOptions = {
from: '"Sender Name" <user@example.com>', // 发件人
to: to, // 收件人
subject: subject, // 主题
text: text // 纯文本内容
};
// 发送邮件
let info = await transporter.sendMail(mailOptions);
console.log('Message sent: %s', info.messageId);
}
// 使用函数发送邮件
sendEmail('recipient@example.com', 'Hello', 'This is a test email.');
如果你需要更高级的功能,如邮件模板、用户跟踪等,可以考虑使用专门的邮件营销服务。
领取专属 10元无门槛券
手把手带您无忧上云