基于Node.js 的nodemailer 发邮件功能
nodemailer 简介
nodemailer 是一个基于node.js 的模块,它能使你发送邮箱十分简单
可以通过在webstorm的命令终端输入npm install nodemailer
引入模块
具体实现
1.使用SMTP或其他某种传输机制创建Nodemailer传输器
2.设置消息选项
3.使用先前创建的传输器的sendMail()方法传递消息对象
const nodemailer = require("nodemailer");
// async..await is not allowed in global scope, must use a wrapper
exports.main=async function (email,title,content) {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let href='http://localhost:8080/verify?id='+userId+'&verifyCode='+verifyCode
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.163.com",
port: 25,
secure: false, // true for 465, false for other ports
auth: {
user: "w_megumin", // generated ethereal user
pass: "DBXZTKTDOCJ****", // generated ethereal password
},
});
console.log('发送消息');
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Megumin👻" <w_megumin@163.com>', // sender address
to: email.toString(), // list of receivers
subject: title, // Subject line
text: content, // plain text body
// html:html,
html: "<a href="+href+">"+ content+"</a>",// html body
});
console.log("Message sent: %s", info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
//main().catch(console.error);
解释一下以上代码
一.创建一个可重复的传送对象默认是使用smtp传输(简单的说就是通过你的邮箱给别人发送邮件)
这里以163邮箱为例
let transporter = nodemailer.createTransport({
host: "smtp.163.com",
port: 25,
secure: false, // true for 465, false for other ports
auth: {
user: "w_megumin", // generated ethereal user
pass: "DBXZTKTDOCJYJNOD", // generated ethereal password
},
});
host:
prot
随意选择只要未被占用就好
secure
安全端口或者其他的什么东西(没了解),选择false就好
auth
开启smtp服务的验证
它会让你扫码发送一条短信,发送成功后出现以下界面
将你的用户名和授权码填入auth里
二.设置短信内容
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <foo@example.com>', // sender address
to: "bar@example.com, baz@example.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
});
from发送者的地址
***<>***里要填写自己的邮箱地址
to 接收者的地址
填入你要发送的地址 ps:我实验的时候,有时候会报错,系统会认为我的短信是垃圾信息。 解决办法:在接收者地址后面再加上自己的邮箱地址。
三.使用
在你需要发送邮件的地方引入(具体地址要自己更改)
发送邮件