Preparation
Because nodemailer is based on node service, you need to install node.js version >=8 or above.
Download nodemailer in Nodejs project
npm i nodemailer
Mailbox configuration process:
Here I take QQ mailbox as an example
1. Open the SMTP service
Location: Mailbox Settings -> Account -> Scroll down to find the SMTP configuration, as shown below
Open service: POP3/SMTP service
will generate a series of authorization codes after opening, we will copy it first
Next enter the code module
// app/config/config.default.js
// qq邮箱配置
config.qqEmail = {
host: 'smtp.qq.com', // QQ邮箱的SMTP地址
port: 465, // 邮箱的端口号一般都使用465,
auth: {
user: '[email protected]', // 你自己的邮箱的邮箱地址
pass: 'lelsutwwbhg', // 授权码
},
};
// app/extend/helper.js
/**
* 发邮件
* @param {Object}
*/
sendEmail(mailOptions) {
const transporter = nodemailer.createTransport(this.app.config.qqEmail);
transporter.sendMail(mailOptions, function(error, info)
if (!err) {
return {
code:0, msg: "验证码发送成功" , info}
} else {
return {
code:1, msg: "验证码发送失败,请稍后重试" , error}
}
});
},
/**
*生成*位随机数 默认为6位
* @param {number} length
*/
rand(length = 6) {
let Num = '';
for (let i = 0; i < length; i++) {
Num += Math.floor(Math.random() * 10);
}
return Num;
},
// app/service/sendEmail.js
'use strict';
const Service = require('egg').Service;
class sendEmailService extends Service {
async sendEmail(account) {
const {
app, ctx } = this;
//要发送的收件人地址
const account = '[email protected]'
// 生成6位验证码
const code = ctx.helper.rand(6); // 该辅助方法在extend/helper.js中定义
// 定义模版
const email = {
title: '某某网---邮箱验证码',
body: `
<h1>尊敬的:${
account}用户</h1>
<p style="font-size: 18px;color:#000;">
您的验证码为:
<span style="font-size: 20px;color:#f00;"> ${
code}, </span>
您当前正在某某网站注册账号,验证码告知他人将会导致数据信息被盗,请勿泄露
</p>
<p style="font-size: 1.5rem;color:#999;">该验证码5分钟内有效,请勿泄漏于他人!</p>
`,
};
const emailCotent = {
from: '[email protected]', // 发件人地址
to: `${
account}`, // 收件人地址,多个收件人可以使用逗号分隔
subject: email.title, // 邮件标题
html: email.body, // 邮件内容
};
return await ctx.helper.sendEmail(emailCotent);// 该辅助方法在extend/helper.js中定义
}
module.exports = sendEmailService;
// app/controller/sendEmail.js
'use strict';
const Controller = require('egg').Controller;
class sendController extends Controller {
// 发送邮件
async send() {
const {
ctx } = this;
const result = await ctx.service.sendEmail();
ctx.body={
code:result.code,
msg:result.msg
}
}
module.exports = sendController;
// app/router.js
'use strict';
module.exports = app => {
const {
router, controller } = app;
// 发送邮件路由
router.post('/api/send/email', controller.sendEmail.send);
};
The effect after sending successfully: