0、介绍
Nodemailer 是 Node.js 应用程序的一个模块,可以方便地发送电子邮件。
该项目于 2010 年开始,至今已经相当稳定,这也是如今大多数 Node.js 用户默认情况下发送邮件的解决方案。
下面介绍如何在eggjs中使用nodemailer
1、安装
npm install nodemailer --save
2、邮箱授权
进入邮箱 》 设置 》 账户 》POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
开启POP3/SMYP服务,获取授权码
3、配置config
在config.default.js中写入以下配置
config.email = {
host: 'smtp.163.com', //邮件host
name: 'xxx@163.com', // 邮件名
password: 'ECGWYISCQNBSYDMW', // vcamessage@163.com Vca123456 ,授权码登录
to:'184336166@qq.com,xxx@163.com' //发送给谁
};
4、封装
在位置 /service/utils/emailUtil 进行封装
'use strict';
const Service = require('egg').Service;
const nodemailer = require('nodemailer');
class EmailUtilService extends Service {
async sendMail(phone, subject,text) { //nodemailer方式
const transport = nodemailer.createTransport({
host: this.config.email.host,
// secureConnection: true, // use SSL
port: 465,
secure: true,
auth: {
user: this.config.email.name,
pass: this.config.email.password
}
});
const message = {
from: this.config.email.name, // Sender address
to: this.config.email.to, // List of recipients
subject: subject, // Subject line
html: `用户账号:${text.phone}<br>用户昵称:${text.nick_name}<br>联系方式:${text.contact}<br>反馈信息:${text.feedback}<br>反馈时间:${this.ctx.helper.formatTime()}` // Plain text body
};
console.log('message:', message);
// console.log('transport:', transport);
transport.sendMail(message, function (err, info) {
if (err) {
console.log('err:');
console.log(err);
} else {
console.log(info);
}
});
}
}
module.exports = EmailUtilService;
5、使用
在container中调用service的utils方法即可
const sendEmailawRes = await ctx.service.utils.emailUtil.sendMail(params.contact,'用户问题反馈('+ params.phone + ')',params);
if(sendEmailawRes){
ctx.body={
message: '发送成功',
code:0
};
}else{
ctx.body={
message: '发送失败',
code:-1
};
}