天天看点

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://[email protected]:[email protected]',
				defaults: {
					from: '"domain.com" <[email protected]>'
				},
				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://[email protected]:[email protected]', 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: '[email protected]', // 接收信息的邮箱
            from: '[email protected]', // 要发送邮件的邮箱
            subject: 'Love You √',
            // html: '<b>welcome !</b>',
            template: 'email',
        })
    }
}
           

模板内容

在src根目录下template/email.pug

doctype html
html()
    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();
    }
}
           

效果截图

nestjs利用定时任务发送邮件
nestjs利用定时任务发送邮件