Nodemailer 是 Node.js 最流行的郵件發送模組,支援 SMTP、sendmail、Amazon SES 等傳輸方式。以下以 QQ 郵箱 SMTP 為例,說明安裝、設定、發送流程與常見錯誤排查。
npm install nodemailer --save
const nodemailer = require('nodemailer');
// 建立 SMTP 連線池
const transporter = nodemailer.createTransport({
host: 'smtp.qq.com',
port: 465,
secure: true, // SSL
auth: {
user: 'your_email@qq.com', // 你的 QQ 郵箱
pass: 'your_auth_code' // 不是登入密碼,是「授權碼」
}
});
// 郵件內容
const mailOptions = {
from: '"Fred Foo" <your_email@qq.com>',
to: 'recipient1@qq.com, recipient2@126.com',
subject: 'Hello World',
html: '<b>Thanks for visiting!</b> 世界,你好!'
};
// 發送
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log('發送失敗:', error);
}
console.log('發送成功:', info.messageId);
// 關閉連線池(長運行程式通常不關閉,複用連線)
// transporter.close();
});
pass 欄位(非 QQ 登入密碼)。| 錯誤訊息 | 原因 | 解決 |
|---|---|---|
| AuthError: Invalid login - 454 Authentication failed, please open smtp flag first! | 未開啟 SMTP 服務或授權碼錯誤 | 開啟 SMTP 服務、確認授權碼正確 |
| SenderError: Mail from command failed - 501 mail from address must be same as authorization user | 發件人郵箱與認證帳號不一致 | from 必須與 auth.user 相同 |
| ETIMEDOUT / ECONNECTION | 網路不通、防火牆阻擋 465/587 埠 | 檢查伺服器網路、安全群組、嘗試 port 587 + secure:false |
| Invalid recipients | 收件人格式錯誤 | 確認 email 格式、多筆用逗號分隔 |
attachments: [{ filename: 'report.pdf', path: './report.pdf' }]attachments: [{ filename: 'logo.png', path: './logo.png', cid: 'logo' }],HTML 中用 <img src="cid:logo">。text: '純文字內容'。await transporter.sendMail(...)(需 Node 8+)。