类库依赖
npm install nodemailer --save
导入
const nodemailer = require("nodemailer");
关键点
- 配置 nodemailer.createTransport 的参数,指定 服务地址,端口号,验证的账户和密码
- 配置 mailOptions ,from , to 指定发送和目标,邮件内容等。
编写代码示例
"use strict";
const nodemailer = require("nodemailer");
const MailSettings = require("../config/MailSettings");
// async..await is not allowed in global scope, must use a wrapper
async function sendMailTo(mailUserName, mailContent){
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let account = await MailSettings.createSenderAccount();
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.qiye.163.com",
port: 994,
secure: true, // true for 465, false for other ports
auth: {
user: account.user, // generated ethereal user
pass: account.pass // generated ethereal password
},
});
// setup email data with unicode symbols
let mailOptions = {
from: '中寰App通知公共邮箱 <app_notice@aerozhonghuan.com>', // sender address
to: `${mailUserName}@aerozhonghuan.com`, // list of receivers
subject: mailContent.subject, // Subject line
// text: mailContent.text, // plain text body
html: mailContent.html // html body
};
// send mail with defined transport object
let info = await transporter.sendMail(mailOptions);
console.log("Message sent: %s", info.messageId);
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
/* 使用 DEMO
let mail = {
subject: "验证码", // Subject line
html: "你的验证码是 <B>123</B>", // plain text body
}
sendMail('zhangyunfei',mail).catch(console.error);
*/
参考
https://nodemailer.com/about/