本章节咱们在项目上集成mail,实现发送邮件功能html
个人经常使用邮箱是126邮箱, 若是须要在项目上使用这个邮箱发送邮件,须要开启SMTP服务。node
1 开启SMTP服务npm
在设置中找到POP3/SMTP/IMAP,页面以下,开启IMAP/SMTP服务,若是已开启,增长一组受权密码,复制下来,由于此密码只显示一次。服务器
2 安装依赖文件app
yarn add @nestjs-modules/mailer nodemailer #or npm install --save @nestjs-modules/mailer nodemailer
3 配置ide
在app.module中配置this
// 邮件 import { MailerModule } from '@nestjs-modules/mailer'; import { PugAdapter } from '@nestjs-modules/mailer/dist/adapters/pug.adapter'; @Module({ imports: [ MailerModule.forRoot({ transport: { host: 'smtp.126.com', port: 25, ignoreTLS: true, secure: false, auth: { user: '你的邮箱地址', pass: '刚才复制的密码', }, }, defaults: { from: '"名字" <你的邮箱地址>', }, preview: false, template: { dir: process.cwd() + '/template/', adapter: new PugAdapter(), // or new PugAdapter() or new EjsAdapter() options: { strict: true, }, }, }) ], controllers: [AppController], providers: [AppService], })
我只演示此功能须要用到的,3d
4 编写发送服务code
新建mail文件夹,文件夹下新建mail.service.ts文件,内容以下htm
import { Injectable } from '@nestjs/common'; import { MailerService } from '@nestjs-modules/mailer'; @Injectable() export class ExampleService { constructor(private readonly mailerService: MailerService) {} /** * 邮件发送 */ public example(subject: string, text: string, html: string): void { this.mailerService .sendMail({ to: '目标邮箱', from: '发送邮箱', subject: subject, text: text, html: html, }) .then(() => {}) .catch(() => {}); } }
5 发送邮件
须要在用到的地方增长
// 导入邮件 import { ExampleService } from '../mail/mail.service'; @Injectable() export class UserService { constructor( private readonly exampleService: ExampleService, ) {} }
调用
this.exampleService.example('主题', '主题', '内容');