基于Nestjs实现node发送邮件
背景
效果
落地方案
-
依赖安装
shellnpm install @nestjs-modules/mailer
-
初始化
module
javascript// app.module.ts @Module({ imports: [ MailerModule.forRoot({ transport: { host: 'smtp.exmail.qq.com', port: 465, ignoreTLS: false, secure: true, auth: { user: 'bot@fmlg1688.cn', pass: 'xxxxxx', }, }, defaults: { from: '"Bot" <bot@fmlg1688.cn>', }, preview:false, template: { dir: path.join(process.cwd(), './src/common/template'),//这里就是你的ejs模板文件夹路径 adapter: new EjsAdapter(), options: { strict: true //严格模式 } } }) ], ... }) export class AppModule { }
-
邮件模版
javascript// common/template/validate.ejs <div class="biu-nav-email" style="max-width: 600px;min-width: 300px;margin: 40px auto;box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);font-size: 16px;border-radius: 5px;color: #ccc;"> <h3 style="margin-bottom: 40px;"> Hi! 亲爱的用户: </h3> <p style="padding-left: 20px;"> 您正在进行邮箱验证,本次请求的验证码为: </p> <p style="color: #dde2e2;padding-left: 14px;"> <strong style="color: #000;font-size: 24px;"> <%= locals.code %> </strong> <span>(为了保障您帐号的安全性,请在30分钟内完成验证,祝您生活愉快!)</span> </p> <p style="padding-left: 20px;"> <span>快速访问:</span> <a href="https://www.biunav.com" style="color:#fff" target="_blank" rel="noopener noreferrer">https://www.biunav.com</a> </p> </div>
-
发送邮件
javascriptimport { MailerService } from '@nestjs-modules/mailer'; import { Controller, Get } from '@nestjs/common'; @Controller({ path: '/mail' }) export class MailController { constructor(private readonly mailerService: MailerService) {} @Get() async classify() { let result = await this.mailerService .sendMail({ to: '1025534801@qq.com', from: 'bot@fmlg1688.cn', subject: '测试', template: './validate.ejs', context: { code: 3311, }, }) .then((result) => { console.log('---->'); }) .catch((error) => { console.log('error:', error); }); return { code: 0, result }; } }