Node使用Nodemailer傳送郵件的方法實現
阿新 • • 發佈:2020-02-25
電子郵件是—種用電子手段提供資訊交換的通訊方式,是網際網路應用最廣的服務。通過網路的電子郵件系統,使用者可以以非常低廉的價格(不管傳送到哪裡,都只需負擔網費)、非常快速的方式(幾秒鐘之內可以傳送到世界上任何指定的目的地),與世界上任何一個角落的網路使用者聯絡。
在很多專案中,我們都會遇到郵件註冊,郵件反饋等需求。在node中收發電子郵件也非常簡單,因為強大的社群有各種各樣的包可以供我麼直接使用。Nodemailer包就可以幫助我們快速實現傳送郵件的功能。
開始
這裡使用的是qq郵箱,因為qq郵箱的許可權比較好設定一些。
安裝模組
cnpm i nodemailer -S
建立-個SMTP客戶端配置
//引入模組 nodemailer const nodemailer = require('nodemailer') // 建立一個SMTP客戶端配置 const config = { service: "QQ",auth: { // 發件人郵箱賬號 user: '[email protected]',//發件人郵箱的授權碼 這裡可以通過qq郵箱獲取 並且不唯一 pass: 'xxxxxxxxxxx' } }
建立一個SMTP客戶端配置物件
const transporter = nodemailer.createTransport(config)
建立一個收件人物件
// 驗證碼隨機數 let code = Math.random().toString().substr(2,4) const mail = { // 發件人 郵箱 '暱稱<發件人郵箱>' from: `"web"<[email protected]>`,// 主題 subject: '啟用驗證碼',// 收件人 的郵箱 可以是其他郵箱 不一定是qq郵箱 to: '',//這裡可以新增html標籤 html: `您的啟用驗證碼為:$[code],請24小時內有效,請謹慎保管。` }
傳送郵件 呼叫transporter.sendMail(mail,callback)
transporter.sendMail(mail,function(error,info) { if (error) { return console.log(error); } transporter.close() console.log('mail sent:',info.response) })
qq許可權的設定
最後就可以愉快的可以傳送郵件啦
完整程式碼演示
//引入模組 nodemailer const nodemailer = require('nodemailer') // 驗證碼隨機書 let code = Math.random().toString().substr(2,4) // 建立一個SMTP客戶端配置 const config = { service: "QQ",auth: { // 發件人郵箱賬號 user: '[email protected]',//發件人郵箱的授權碼 這裡可以通過qq郵箱獲取 並且不唯一 pass: 'xxxxxxxxxxxxxxxxxxxxxx' //授權碼生成之後,要等一會才能使用,否則驗證的時候會報錯,但是不要慌張哦 } } //建立一個SMTP客戶端配置物件 const transporter = nodemailer.createTransport(config) //建立一個收件人物件 const mail = { // 發件人 郵箱 '暱稱<發件人郵箱>' from: `"web"<[email protected]>`,// 收件人 的郵箱 可以是其他郵箱 不一定是qq郵箱 to: '[email protected]',請24小時內有效,請謹慎保管。` } // 傳送郵件 呼叫transporter.sendMail(mail,callback) transporter.sendMail(mail,info.response) })
到此這篇關於Node使用Nodemailer傳送郵件的方法實現的文章就介紹到這了,更多相關Nodemailer傳送郵件內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!