天天看點

node.js 使用nodemailer發送qq郵件

實作nodemailer發送郵件給qq郵箱

安裝環境

這裡分享筆者的版本,各位可以根據需求更改

  • node – 10.15.3
  • express – 4.16.4
  • nodemailer --6.1.0

注意:筆者隻使用了一個index.js檔案,以下代碼合并在一個頁面後即可運作.可以根據個人需求分頁開發

配置傳送服務

let mailTransport = nodemailer.createTransport({
    // host: 'smtp.qq.email',
    service:'qq',
    secure: true,	//安全方式發送,建議都加上
    auth: {
        user: '[email protected]',
        pass: '*************'
    }
})
           
  • 配置中的auth用于配置用于發送郵件的郵箱,這裡使用的是qq郵箱
  • user即你的qq郵箱位址,xxxxxxxx表示qq号
  • 注意,這裡的pass并不是你的qq密碼,而是在qq郵箱中開啟SMTP服務時提供的授權碼,具體開啟步驟如下

開啟QQ郵箱SMTP

  • 登入QQ郵箱
  • 點選左上角設定
  • 選擇賬戶欄往下翻
  • 有一個POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務欄,選擇IMAP/SMTP服務開啟選項,如圖.記得記錄給你的授權碼,填入pass
    node.js 使用nodemailer發送qq郵件

引入需要的子產品并開啟app

let nodemailer = require('nodemailer');
let express = require('express');
let app = express();

           

建立通路位址

app.get('/send',function(req,res) {
    let options = {
        from: ' "zhy" <[email protected]>',
        to: '<[email protected]>',
        bcc: '密送',
        subject: 'node郵件',
        text: 'hello nodemailer',
        html: '<h1>hello zhy</h1>'
    };
    mailTransport.sendMail(options,function(err,msg) {
        if(err) {
            console.log(err);
            res.send(err);
        } else {
            res.send('success');
        }
    })
});
           
  • from表示發送方,也就是你的郵箱,zhy表示名稱,選擇性填寫
  • to表示接收方,也就是想要發送給誰
  • subject是郵件标題
  • text是郵件内容,如果包含html會被覆寫
  • html以html後的内容顯示在郵件正文

監聽端口

app.listen(8000,function() {
    console.log('running...');
})
           

接下來就可以通過開啟服務并通路localhost:8000/send來發送郵件了,可以到接收方郵箱中檢視

node.js 使用nodemailer發送qq郵件

繼續閱讀