经常忘事,做了个代办事项提醒,使用eggjs作为后台服务,nodejs利用QQ邮箱发邮件来进行消息接收。
1.在eggjs项目service下新建一个文件,使用npm安装 nodemailer;
user_email是发送账号,auth_code是授权码;
'use strict';
const Service = require('egg').Service;
const nodemailer = require('nodemailer');
const user_email = 'xxx@qq.com';
const auth_code = 'xxxxx';
const transporter = nodemailer.createTransport({
service: 'qq',
secureConnection: true,
port: 465,
auth: {
user: user_email, // 账号
pass: auth_code, // 授权码
},
});
class EmallService extends Service {
async sendMail(email, subject, text, html) {
const mailOptions = {
from: user_email, // 发送者,与上面的user一致
to: email, // 接收者账号,可以同时发送多个,以逗号隔开
subject, // 标题
text, // 文本
html,
};
try {
await transporter.sendMail(mailOptions);
return true;
} catch (err) {
return false;
}
}
}
module.exports = EmallService;
2.在Controller中引用就行
class emallController extends Controller {
async emall() {
const email = 'xxxx@qq.com'; // 接收者的邮箱
const subject = 'xxx生日提醒';
const text = '文本';
const html = '<h2>测试一下::</h2><a class="elem-a" ><span class="content-elem-span">测试链接</span></a>';
//在此处调用。适当的改一下service路径
const has_send = await this.service[this.app.config.public].admin.emall.sendMail(email, subject, text, html);
if (has_send) {
await this.ctx.returnBody(has_send, 200, '发送成功');
return;
}
await this.ctx.returnBody(has_send, 400, '发送失败');
}
}
|