如何使用NodeJS發送郵件

1.安裝依賴包 這裏用的是nodemailer
npm install nodemailer
2.使用qq郵箱,先到郵箱設置-》賬戶中開啓POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務
獲得授權碼

下面代碼是ts 寫的
1、不使用ssl

import nodemailer = require("nodemailer");
import SMTPTransport = require("nodemailer/lib/smtp-transport");
import Mail = require("nodemailer/lib/mailer");
let option: SMTPTransport.Options = {
    host: "smtp.qq.com",
    service: "smtp.qq.com",
    port: 25,
    ignoreTLS: true,
    requireTLS: true,
    auth: {
        user: "[email protected]",
        pass: "xxxxxxxxxxxxxxx"//授權碼
    }
}

let mailInfo: Mail.Options = {
    from: "[email protected]",
    to: "[email protected]",
    subject: "測試111",
    text: "fsfs"
}
let transport = nodemailer.createTransport(option);
transport.sendMail(mailInfo, (err, info) => {
    if (err) {
        console.log(err);
    }
    else {
        console.log("send success")
    }
})

2、使用ssl 只需要把上面的參數改下

let option: SMTPTransport.Options = {
    host: "smtp.qq.com",
    service: "smtp.qq.com",
    port: 465,
    secure: true,
    auth: {
        user: "[email protected]",
        pass: "xxxxxxxxxxxxxxx"//授權碼
    }
}

注意:有時出現問題,建議先用foxmail 試試可不可以登錄,能登陸的話 按foxmail的參數來設置就可以了。

發佈了11 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章