配置邮件服务器先决条件2012_【Nest教程】Nest项目配置邮件服务器,实现发送邮件...

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

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

1 开启SMTP服务

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

15320a25983f2c5c91a84f995d01abcf.png

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('主题', '主题', '内容');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值