nodemailer 的使用

NodeMailer

概念介绍

NodeMailer 是一个用于 Node.js 的邮件发送库, 通过连接 SMTP 协议,与指定的邮件服务商(QQ、163、Gmail 等)的 SMTP 服务器建立安全连接,并 代理 开发者完成邮件的提交与投递(先提交再投递)

1
2
3
4
5
6
7
8
9
let transport = nodemailer.createTransport({
host: 'smtp.qq.com', // ← 1. 指定 SMTP 服务器地址
port: 465, // ← 2. 使用 SMTPS(SMTP over SSL)端口
secure: true, // ← 3. 启用 TLS/SSL 加密
auto: {
user: 'your_email@example.com', // ← 4. 身份认证:邮箱账号
pass: 'your_smtp_auth_code' // ← 5. 身份认证:授权码(非登录密码!)
}
})

当执行:

1
await transport.sendMail(mailOptiion)

nodemailer 会:

  1. 建立 TCP 连接smtp.qq.com:465
  2. 自动协商 SSL/TLS 加密通道(因为 secure: true
  3. 发送 SMTP 命令序列
    • EHLO → 握手
    • AUTH LOGIN → 使用 Base64 编码发送 userpass
    • MAIL FROM:<from@example.com → 声明发件人
    • RCPT TO:<to@example.com> → 声明收件人
    • DATA → 发送邮件头 + 正文
    • QUIT → 断开连接
  4. 将邮件提交给 QQ 邮箱的 SMTP 服务器
  5. 由 QQ 邮箱系统负责最终投递到目标邮箱(如 163、Gmail、Outlook 等)

nodemailer 不直接投递到收件人邮箱,而是把邮件“交给”你配置的 SMTP 服务商(这里是 QQ),由它完成后续路由和投递。

一句话总结就是:

✅ **nodemailer 是一个 SMTP 客户端库,它封装了 SMTP 协议的底层通信细节,让你能用简单的 JavaScript 对象配置,即可通过任意支持 SMTP 的邮件服务商(如 QQ、163、SendGrid、Amazon SES 等)发送邮件。

Nodemailer 使用流程(5 步)

第 1 步:安装依赖

1
npm install nodemailer

⚠️ 注意:仅用于服务端(Node.js),不能在浏览器中使用(涉及 SMTP 密钥,且浏览器无 TCP 权限)。


第 2 步:创建传输器(Transporter)

配置 SMTP 服务器连接信息:

1
2
3
4
5
6
7
8
9
let transport = nodemailer.createTransport({
host: 'smtp.qq.com', // ← 1. 指定 SMTP 服务器地址
port: 465, // ← 2. 使用 SMTPS(SMTP over SSL)端口
secure: true, // ← 3. 启用 TLS/SSL 加密
auto: {
user: 'your_email@example.com', // ← 4. 身份认证:邮箱账号
pass: 'your_smtp_auth_code' // ← 5. 身份认证:授权码(非登录密码!)
}
})

🔐 授权码获取方式(以 QQ 邮箱为例):

  1. 登录 QQ 邮箱 → 设置 → 账户
  2. 开启 “POP3/SMTP 服务” → 按提示生成 16 位授权码

第 3 步:定义邮件内容(Mail Options)

1
2
3
4
5
6
7
const mailOptions = {
from: '"Your App" <your_email@qq.com>', // 发件人(必须与 auth.user 一致或别名)
to: 'recipient@example.com', // 收件人(可多个:'a@x.com, b@y.com')
subject: '验证码', // 邮件标题
text: '您的验证码是:123456', // 纯文本正文
// html: '<b>您的验证码是:123456</b>' // HTML 正文(可选,优先级高于 text)
};

📌 关键规则:

  • from 中的邮箱地址 必须与 auth.user 一致,否则会被 SMTP 服务器拒绝。
  • 可同时提供 texthtml,客户端会优先显示 html

第 4 步:发送邮件(异步)

1
2
3
4
5
6
7
8
9
10
11
12
async function sendEmail() {
try {
const info = await transporter.sendMail(mailOptions);
console.log('Message sent: %s', info.messageId);
// 示例输出: Message sent: <b658f8ca-4d9e-11ea-8f00-0a0b12345678@qq.com>
} catch (error) {
console.error('Send email failed:', error);
// 常见错误:认证失败、网络超时、配额超限
}
}

sendEmail();

💡 返回的 info 包含邮件 ID、响应状态等,可用于日志或追踪。


第 5 步(可选):验证 SMTP 配置是否有效

1
2
3
4
5
6
7
8
// 测试连接(不发邮件)
transporter.verify((error, success) => {
if (error) {
console.log('SMTP config error:', error);
} else {
console.log('SMTP server is ready to take messages');
}
});


nodemailer 的使用
https://dxblacksmith.github.io/2026/01/31/nodemailer/
作者
DxBlackSmith
发布于
2026年1月31日
许可协议