|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const Service = require('egg').Service; |
| 4 | +const mailer = require('nodemailer'); |
| 5 | +const smtpTransport = require('nodemailer-smtp-transport'); |
| 6 | + |
| 7 | + |
| 8 | +class MailService extends Service { |
| 9 | + async sendMail(data) { |
| 10 | + const { config, logger } = this; |
| 11 | + |
| 12 | + if (config.debug) { |
| 13 | + return; |
| 14 | + } |
| 15 | + |
| 16 | + const transporter = mailer.createTransport(smtpTransport(config.mail_opts)); |
| 17 | + |
| 18 | + for (let i = 1; i < 6; i++) { |
| 19 | + try { |
| 20 | + await transporter.sendMail(data); |
| 21 | + logger.info('send mail success', data); |
| 22 | + break; |
| 23 | + } catch (err) { |
| 24 | + if (i === 5) { |
| 25 | + logger.error('send mail finally error', err, data); |
| 26 | + throw new Error(err); |
| 27 | + } |
| 28 | + logger.error('send mail error', err, data); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + async sendActiveMail(who, token, name) { |
| 34 | + const { config } = this; |
| 35 | + const from = `${config.name} <${config.mail_opts.auth.user}>`; |
| 36 | + const to = who; |
| 37 | + const subject = config.name + '社区帐号激活'; |
| 38 | + const html = '<p>您好:' + name + '</p>' + |
| 39 | + '<p>我们收到您在' + config.name + '社区的注册信息,请点击下面的链接来激活帐户:</p>' + |
| 40 | + '<a href = "' + config.host + '/active_account?key=' + token + '&name=' + name + '">激活链接</a>' + |
| 41 | + '<p>若您没有在' + config.name + '社区填写过注册信息,说明有人滥用了您的电子邮箱,请删除此邮件,我们对给您造成的打扰感到抱歉。</p>' + |
| 42 | + '<p>' + config.name + '社区 谨上。</p>'; |
| 43 | + |
| 44 | + await this.sendMail({ |
| 45 | + from, |
| 46 | + to, |
| 47 | + subject, |
| 48 | + html, |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | + async sendResetPassMail(who, token, name) { |
| 54 | + const { config } = this; |
| 55 | + const from = `${config.name} <${config.mail_opts.auth.user}>`; |
| 56 | + const to = who; |
| 57 | + const subject = config.name + '社区密码重置'; |
| 58 | + const html = '<p>您好:' + name + '</p>' + |
| 59 | + '<p>我们收到您在' + config.name + '社区重置密码的请求,请在24小时内单击下面的链接来重置密码:</p>' + |
| 60 | + '<a href="' + config.host + '/reset_pass?key=' + token + '&name=' + name + '">重置密码链接</a>' + |
| 61 | + '<p>若您没有在' + config.name + '社区填写过注册信息,说明有人滥用了您的电子邮箱,请删除此邮件,我们对给您造成的打扰感到抱歉。</p>' + |
| 62 | + '<p>' + config.name + '社区 谨上。</p>'; |
| 63 | + |
| 64 | + await this.sendMail({ |
| 65 | + from, |
| 66 | + to, |
| 67 | + subject, |
| 68 | + html, |
| 69 | + }); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +module.exports = MailService; |
| 74 | + |
0 commit comments