天天看點

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利用定時任務發送郵件