【Nest教程】Nest项目配置邮件服务器,实现发送邮件

本章节我们在项目上集成mail,实现发送邮件功能

我的常用邮箱是126邮箱, 如果需要在项目上使用这个邮箱发送邮件,需要开启SMTP服务。

1 开启SMTP服务

在设置中找到POP3/SMTP/IMAP,页面如下,开启IMAP/SMTP服务,如果已开启,增加一组授权密码,复制下来,因为此密码只显示一次。

【Nest教程】Nest项目配置邮件服务器,实现发送邮件

2 安装依赖文件


yarn add @nestjs-modules/mailer nodemailer
#or
npm install --save @nestjs-modules/mailer nodemailer

3 配置

在app.module中配置

// 邮件
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],
})

我只演示此功能需要用到的,

4 编写发送服务

新建mail文件夹,文件夹下新建mail.service.ts文件,内容如下


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('主题', '主题', '内容');
上一篇:【Nest教程】Nest项目集成JWT接口认证


下一篇:c#-NEST弹性搜索中的Lambda查询具有过滤器和值的数组