nestjs利用定时任务发送邮件

本文介绍如何在NestJS项目中配置邮件服务,包括安装邮件模块、模板引擎,创建邮件模块、控制器和服务,配置邮件模块及定时任务等。

邮件服务

安装邮件模块
yarn add @nestjs-modules/mailer nodemailer
#or
npm install --save @nestjs-modules/mailer nodemailer
安装模板引擎
yarn add handlebars
#or
yarn add pug
#or
yarn add ejs
新建邮件模块、控制器、服务
nest g module modules/email
nest g co modules/email --no-spec
nest g service modules/email --no-spec
配置邮件模块

app.module.ts

import { MailerModule } from '@nestjs-modules/mailer'
import { PugAdapter} from '@nestjs-modules/mailer/dist/adapters/pug.adapter'
import { EmailModule } from './modules/email/email.module';
import * as path from 'path';

@Module({
	imports: [
		EmailModule,
		MailerModule.forRootAsync({
			useFactory: () => ({
				transport: 'smtps://xxx@qq.com:cfooznddrnnncihj@smtp.qq.com',
				defaults: {
					from: '"domain.com" <no-reply@domain.com>'
				},
				template: {
                    // dir: process.cwd() + '/src/template/', // 这一句不用配置,可以找到路径
                    dir: path.join(__dirname, './template'),
					adapter: new PugAdapter(),
					options: {
						strict: true
					}
				}
			})
		})
	],
	controllers: [AppController],
	providers: [AppService],
})
export class AppModule { }

注意:

  1. transport: 'smtps://3472569282@qq.com:cfooznddrnnncihj@smtp.qq.com', a. cfooznddrnnncihj这个需要在邮箱设置中允许配置获取秘钥

  2. 使用dir: path.join(__dirname, './template')会提示在dist路径下找不到,需要在nest-cli.json中配置:

    {
      "collection": "@nestjs/schematics",
      "sourceRoot": "src",
      "compilerOptions": {
          "assets": ["template/**/*"]
      }
    }
    
配置控制器
import { Controller, Get } from '@nestjs/common';
import { EmailService } from './email.service';

@Controller('email')
export class EmailController {
    
    constructor(private readonly emailService: EmailService) {}

    @Get()
    sendEmail() {
        this.emailService.sendEmail();
        return 'ok';
    }
}
配置服务
import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';

@Injectable()
export class EmailService {

    constructor(private readonly mailerService: MailerService) {}

    sendEmail () {
        this.mailerService.sendMail({
            to: 'xxx@163.com', // 接收信息的邮箱
            from: 'xxx@qq.com', // 要发送邮件的邮箱
            subject: 'Love You √',
            // html: '<b>welcome !</b>',
            template: 'email',
        })
    }
}
模板内容

在src根目录下template/email.pug

doctype html
html(lang="en")
    head
        title 嗨
    body
        h1 cute girl
        #container.col
        p 喜
        p 欢
        p 你
        ul
            li LOVE YOU .
        img(src="https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2903795984,3730028115&fm=26&gp=0.jpg")

定时任务

https://docs.nestjs.com/techniques/task-scheduling

安装地址
npm install --save @nestjs/schedule
配置

将ScheduleModule导入到根目录AppModule并运行forRoot()静态方法
tasks.module.ts

import { Module } from '@nestjs/common';
import { TasksService } from './tasks.service';
import { ScheduleModule } from '@nestjs/schedule';
import { EmailService } from '../email/email.service';
@Module({
  providers: [TasksService, EmailService],
  imports: [ScheduleModule.forRoot()]
})
export class TasksModule {}
服务配置

tasks.service.ts

import { Injectable, Logger } from '@nestjs/common';
import { Cron, Interval, Timeout} from '@nestjs/schedule';
import { EmailService } from '../email/email.service';

@Injectable()
export class TasksService {
    private readonly logger = new Logger(TasksService.name)
    
    constructor(private readonly emailService: EmailService) {}

    @Cron('45 * * * * *')
    handleCron() {
        this.logger.debug('该方法将在45秒标记处每分钟运行一次');
    }

    @Interval(10000)
    handleInterval() {
        this.logger.debug('2');
    }

    @Timeout(5000)
    handleTimeout() {
        this.logger.debug('3')
    }

    @Interval(10000)
    sendEmail() {
        this.emailService.sendEmail();
    }
}

效果截图

在这里插入图片描述
在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值