嘗試用了Nodemailer來發送郵件,結果成功了,雖然是相對比較簡單的,但還是記錄一下吧。
Nodemailer 是 Node.js 應用程序的一個模塊,可以方便地發送電子郵件。
使用
# 初始化 pageage.json 文件
$ npm init
# 安裝依賴
$ npm install nodemailer --save
# 運行
node app.js
app.jsconst nodemailer = require('nodemailer');//開啟SMTP連接池
let transporter = nodemailer.createTransport({host: 'smtp.qq.com',secureConnection: true, //use SSLport: 465,secure: true, //secure: true for port 465, secure:false for port 587auth: {user: '987905457@qq.com',pass: 'xxxx' //qq授權碼}
});//設置郵件內容(誰發送什么給誰)
let mailOptions = {from: '"謝麗丹"<987905457@qq.com>', //發件人to: 'xingxi.xie@gmail.com', //收件人subject: 'Hello', //主題text: '這是一封來自nodejs的測試郵件', //文本內容html: '<b>這是一封來自nodejs的測試郵件</b>', //html body//下面是發送附件,不需要就注釋掉attachments: [{filename: 'test.txt',path: './test.txt',},{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}');
});
由于我是使用qq郵箱來發送郵件的,qq郵箱需要獲取POP3/SMTP服務授權碼。