天天看点

eggjs 使用nodemailer发送邮件

最近在用eggjs做后台开发,正好遇到需要发送邮件的功能,再此记录一下

1. 下载 nodemailer

npm install nodemailer --save
           

2. 邮箱授权

当然,要发送邮件,我们需要有自己的邮箱,并且要去获取到授权码

这里以QQ邮箱为例:

进入邮箱 》 设置 》 账户 》POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务

开启POP3/SMYP服务,获取授权码

eggjs 使用nodemailer发送邮件

3. 使用nodemailer

获得授权码后,我们就可以测试一下了

// 这里举简单例子,也可以封装成service来调用
// 引入nodemailer
const nodemailer = require('nodemailer');

// 封装发送者信息
const transporter = nodemailer.createTransport({
  service: 'qq', // 调用qq服务器
  secureConnection: true, // 启动SSL
  port: 465, // 端口就是465
  auth: {
    user: '[email protected]', // 账号
    pass: 'xxxxxxxxxx', // 授权码,

  },
});

// 邮件参数及内容
const mailOptions = {
  from: '[email protected]', // 发送者,与上面的user一致
  to: '[email protected]', // 接收者,可以同时发送多个,以逗号隔开
  subject: '测试的邮件', // 标题
  // text: '测试内容', // 文本
  html: '<h2>测试一下:</h2><a class="elem-a" href="https://baidu.com" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" ><span class="content-elem-span">测试链接</span></a>',
};

// 调用函数,发送邮件
await transporter.sendMail(mailOptions, function(err, info) {
  if (err) {
    console.log(err);
    return;
  }
  console.log(info);

});
           

简单封装

上面是直接使用nodemailer,在实际开发中,我们可以对其进行简单封装,以便调用

在app/service/tool.js文件

// app/service/tool.js

'use strict';

const Service = require('egg').Service;

const nodemailer = require('nodemailer');
const user_email = '[email protected]';
const auth_code = 'xxxxxx';

const transporter = nodemailer.createTransport({
  service: 'qq',
  secureConnection: true,
  port: 465,
  auth: {
    user: user_email, // 账号
    pass: auth_code, // 授权码

  },
});

class ToolService 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 = ToolService;

           

在测试controller中调用, app/controller/test.js

// app/controller/test.js
'use strict';

const Controller = require('egg').Controller;

class TestController extends Controller {
  async testSendMail() {
  	const ctx = this.ctx;
  	
  	const email = '[email protected]';  // 接收者的邮箱
    const subject = '测试邮件';
    const text = '这是一封测试邮件';
    const html = '<h2>测试一下::</h2><a class="elem-a" href="https://baidu.com" target="_blank" rel="external nofollow"  target="_blank" rel="external nofollow" ><span class="content-elem-span">测试链接</span></a>';
    
    const has_send = await this.service.tool.sendMail(email, subject, html);
    
    if (has_send) {
		ctx.body={
			message: '发送成功',
		};
		return;
	}
	ctx.body={
		message: '发送失败',
	};
    
  }

}

module.exports = TestController;
           

这就是简单的发送邮件,这个插件还可以上传附件,详情可参考nodemailer文档:https://nodemailer.com/about/