const nodemailer = require('nodemailer');
const path = require('path');
/**
*
* @param {*} userAccount 个人邮箱的账号 ex. [email protected]
* @param {*} pass 邮箱开启SMTP服务后得到的授权码
* @param {*} to 邮件接收者邮箱账号
* @param {*} params
* @param {*} params.subject 邮件的主题
* @param {*} params.text 邮件的文本内容 可以为空 为空的话,是一个内容为空白的邮件
* @param {*} params.html 邮件的HTML内容 可以为空
*/
const sendMail = ({
userAccount,
pass,
to,
params = {
subject,
text,
html
}
}) => {
if (!userAccount || !pass) {
throw new Error('个人邮箱账号或邮箱授权码不能为空')
}
if (!to) {
throw new Error('邮件接收者邮箱账号不能为空')
}
if (!params || params === {
}) {
throw new Error('邮件内容信息不能为空')
}
var transporter = nodemailer.createTransport({
// 邮箱服务的host: qq: smtp.qq.com; 163: smtp.163.com
host: 'smtp.qq.com',
// 开启安全连接,这个开不开都可以,对安全性有要求的话,最好开启
secureConnection: true,
// SMTP协议端口号
port: 465,
auth: {
user: userAccount,
pass: pass,
},
tls: {
rejectUnauthorized: false, // 拒绝认证就行了, 不然会报证书问题
},
});
// 配置发送内容
var mailOptions = {
// 发件人邮箱
from: userAccount,
// 收件人邮箱, 多个邮箱地址用逗号隔开
to: to,
// 邮件主题
subject: params.subject,
// 文字内容
text: params.text,
// html内容
html: params.html,
// 发送邮箱附件
attachments: [{
// 文件名
filename: 'buffer.js',
// 文件路径
path: './buffer.js'
}, {
filename: '1.jpg',
path: path.resolve(__dirname, '../image/1.jpg')
}, {
filename: 'nodejs.md',
path: path.resolve(__dirname, '../nodejs.md')
}]
}
console.log(mailOptions, "发送内容")
// 发送邮件
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log('发送错误:' + err);
} else {
console.log('邮件发送:' + info.response);
}
});
}
module.exports = {
sendMail
}
nodejs send email operation
Guess you like
Origin blog.csdn.net/weixin_45932157/article/details/130998874
Recommended
Ranking