我的博客原文:https://bxm0927.github.io/201...html
Nodemailer 是 Node.js 應用程序的一個模塊,能夠方便地發送電子郵件。node
該項目於 2010 年開始,至今已經至關穩定,這也是現在大多數 Node.js 用戶默認狀況下發送郵件的解決方案。git
# 初始化 pageage.json 文件 $ npm init # 安裝依賴 $ npm install nodemailer --save # 運行 node app.js
app.jsgithub
const nodemailer = require('nodemailer'); // 開啓一個 SMTP 鏈接池 let transporter = nodemailer.createTransport({ host: 'smtp.qq.com', secureConnection: true, // use SSL port: 465, secure: true, // secure:true for port 465, secure:false for port 587 auth: { user: '80583600@qq.com', pass: 'xxx' // QQ郵箱須要使用受權碼 } }); // 設置郵件內容(誰發送什麼給誰) let mailOptions = { from: '"白小明 ?" <80583600@qq.com>', // 發件人 to: 'xx1@qq.com, xx2@qq.com', // 收件人 subject: 'Hello ✔', // 主題 text: '這是一封來自 Node.js 的測試郵件', // plain text body html: '<b>這是一封來自 Node.js 的測試郵件</b>', // html body // 下面是發送附件,不須要就註釋掉 attachments: [{ filename: 'test.md', path: './test.md' }, { filename: 'content', content: '發送內容' } ] }; // 使用先前建立的傳輸器的 sendMail 方法傳遞消息對象 transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log(`Message: ${info.messageId}`); console.log(`sent: ${info.response}`); });
效果預覽npm
實踐的時候遇到許多問題,如今列舉以下,若未詳盡,敬請留言交流。json
首先須要開啓郵箱的 POP3/SMTP 服務。app
QQ郵箱須要使用受權碼,而不是QQ密碼;163 郵箱直接使用163郵箱密碼就行。測試
進入QQ郵箱,設置-帳戶-開啓服務 POP3/SMTP 服務,並生成受權碼,如今獲取受權碼須要驗證手機短信。ui
理論上支持全部主流郵箱,但我只測試了 QQ 和 163,都成功了。若其餘郵箱出問題請留言交流。spa
Error: Invalid login: 535 Error: authentication failed
認證失敗:
多是帳號密碼錯誤
連接資源池時加 ssl:secureConnection: true,
QQ 的 host 是 smtp.qq.com
;163 的 host 是 smtp.163.com
Error: Mail command failed: 553 Mail from must equal authorized user
發件人和認證的郵箱地址不一致
auth.user 須要與 from 中的郵箱一致