萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js 使用 Nodemailer 發送郵件(QQ 郵箱範例)

Nodemailer 是 Node.js 最流行的郵件發送模組,支援 SMTP、sendmail、Amazon SES 等傳輸方式。以下以 QQ 郵箱 SMTP 為例,說明安裝、設定、發送流程與常見錯誤排查。

1. 安裝

npm install nodemailer --save

2. 發送郵件完整代碼


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();
});

3. 關鍵設定:QQ 郵箱授權碼

  1. 登入 QQ 郵箱網頁版 → 設定 → 帳戶。
  2. 開啟「POP3/SMTP 服務」或「IMAP/SMTP 服務」。
  3. 發送手機驗證碼,獲得 **16 位授權碼**。
  4. 將授權碼填入 pass 欄位(非 QQ 登入密碼)。

4. 常見錯誤與解決

錯誤訊息原因解決
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 格式、多筆用逗號分隔

5. 進階用法

  • 附件:attachments: [{ filename: 'report.pdf', path: './report.pdf' }]
  • 內嵌圖片:attachments: [{ filename: 'logo.png', path: './logo.png', cid: 'logo' }],HTML 中用 <img src="cid:logo">。
  • HTML + 純文字備用:text: '純文字內容'。
  • Promise/Async 風格:await transporter.sendMail(...)(需 Node 8+)。
copyright © 萬盛學電腦網 all rights reserved