使用Nodemailer發送郵件

開始

這裏使用的是qq郵箱,由於qq郵箱的權限比較好設置一些。html

安裝模塊

cnpm i nodemailer -Snode

建立-個SMTP客戶端配置

//引入模塊 nodemailer
 const nodemailer = require('nodemailer')

 // 建立一個SMTP客戶端配置
 const config = {
     service: "QQ",
     auth: {
         // 發件人郵箱帳號
         user: 'xxxxxx@qq.com',
         //發件人郵箱的受權碼 這裏能夠經過qq郵箱獲取 而且不惟一
         pass: 'xxxxxxxxxxx'
     }
 }
複製代碼

建立一個SMTP客戶端配置對象

const transporter = nodemailer.createTransport(config)
複製代碼

建立一個收件人對象

// 驗證碼隨機數 
 let code = Math.random().toString().substr(2, 4)
 const mail = {
     // 發件人 郵箱  '暱稱<發件人郵箱>'
     from: `"web"<xxxx@qq.com>`,
     // 主題
     subject: '激活驗證碼',
     // 收件人 的郵箱 能夠是其餘郵箱 不必定是qq郵箱
     to: '',
     //這裏能夠添加html標籤
     html: `<b>您的激活驗證碼爲:${code}, 請24小時內有效,請謹慎保管。</b>`
 }
複製代碼

發送郵件 調用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: 'xxxxxxxxx@qq.com',
         //發件人郵箱的受權碼 這裏能夠經過qq郵箱獲取 而且不惟一
         pass: 'xxxxxxxxxxxxxxxxxxxxxx'   //受權碼生成以後,要等一會才能使用,不然驗證的時候會報錯,可是不要慌張哦
     }
 }


 //建立一個SMTP客戶端配置對象
 const transporter = nodemailer.createTransport(config)

 //建立一個收件人對象
 const mail = {
     // 發件人 郵箱  '暱稱<發件人郵箱>'
     from: `"web"<xxxxxxxxxx@qq.com>`,
     // 主題
     subject: '激活驗證碼',
     // 收件人 的郵箱 能夠是其餘郵箱 不必定是qq郵箱
     to: 'xxxxxxx@163.com',
     //這裏能夠添加html標籤
     html: `<b>您的激活驗證碼爲:${code}, 請24小時內有效,請謹慎保管。</b>`
 }

 //  發送郵件 調用transporter.sendMail(mail, callback)
 transporter.sendMail(mail, function(error, info) {
         if (error) {
             return console.log(error);
         }
         transporter.close()
         console.log('mail sent:', info.response)
     })

複製代碼
相關文章
相關標籤/搜索