在 JavaScript (Node.js) 中发送电子邮件:nodemailer, sendgrid, mailgun
发送电子邮件是现代 Web 应用程序的关键功能之一:用户注册、密码重置、通知和营销邮件。在 Node.js 生态系统中,有几种经过验证的解决方案可以让您在几分钟内集成邮件功能。在本文中,我们将详细介绍三种流行的工具:nodemailer、sendgrid 和 mailgun。您将了解如何配置 SMTP、发送带有附件和 HTML 模板的邮件,以及需要跟踪哪些指标。
1. Nodemailer — 通用 SMTP 客户端
Nodemailer 是 Node.js 中最流行的发送电子邮件库。它支持 SMTP、SES、Sendmail 和多种传输方式。主要优点:
- 通过 SMTP 账户(Gmail、Yandex、Mail.ru)进行简单配置。
- 支持附件、内嵌图片、HTML 模板。
- 支持队列和连接池。
- 通过
async/await进行异步发送。
安装和基本发送
npm install nodemailerconst nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 587, secure: false, // 对于 465 端口为 true auth: { user: 'your-email@gmail.com', pass: 'your-password' // 或应用密码 }});
const mailOptions = { from: '"发送者" <your-email@gmail.com>', to: 'recipient@example.com', subject: '来自 Node.js 的问候!', text: '这是一封测试邮件。', html: '<h1>你好!</h1><p>这是 HTML 版本。</p>'};
const sendMail = async () => { const info = await transporter.sendMail(mailOptions); console.log('邮件已发送:', info.messageId);};
sendMail().catch(console.error);发送带附件的邮件
const mailOptions = { // ...基本字段 attachments: [ { filename: 'document.pdf', path: '/path/to/document.pdf' }, { filename: 'image.png', content: fs.createReadStream('/path/to/image.png') } ]};重要提示: 对于 Gmail,请使用 应用密码 或 OAuth2。
2. SendGrid — 用于事务性邮件的云服务
SendGrid(Twilio 的一部分)提供强大的 API 来发送具有高送达率的电子邮件。适用于初创公司和大型项目。主要功能:
- 使用访问密钥的 API(无需 SMTP)。
- 动态模板(Handlebars)。
- 分析:打开率、点击率、退订率。
- 免费套餐每天最多 100 封邮件。
安装和发送
npm install @sendgrid/mailconst sgMail = require('@sendgrid/mail');sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = { to: 'recipient@example.com', from: 'sender@example.com', subject: '事务性邮件', text: '邮件正文', html: '<strong>HTML 内容</strong>', attachments: [ { content: 'base64encodedcontent', filename: 'invoice.pdf', type: 'application/pdf', disposition: 'attachment' } ]};
sgMail.send(msg) .then(() => console.log('邮件已发送')) .catch(console.error);使用动态模板
const msg = { to: 'user@example.com', from: 'noreply@mysite.com', templateId: 'd-xxxxxxxxxxxxxxxx', dynamicTemplateData: { username: '伊万', orderLink: 'https://mysite.com/order/123' }};