Nodejs Nestjs邮件发送插件nestjs-mailer的使用

Nodejs Nestjs邮件发送插件nestjs-mailer的使用
nestjs-mailer 是一个用于 NestJS 应用程序的邮件发送库。它基于 nodemailer 库,并提供了 NestJS 风格的模块和提供者。下面是如何在 NestJS 项目中使用 nestjs-mailer 的步骤:

安装

首先,你需要安装 nestjs-mailernodemailer

npm install @ nestjsx/mailer nodemailer

配置

然后,在你的应用程序中配置 MailerModule。你可以通过 MailerOptions 接口来设置邮件服务器的配置。

示例配置

假设你使用的是 Gmail 作为你的邮件服务器:

import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        host: 'smtp.gmail.com',
        port: 465,
        secure: true, // 使用 SSL
        auth: {
          user: 'your-email@gmail.com',
          pass: 'your-password',
        },
      },
      defaults: {
        from: '"nest-modules" <modules@nestjs.com>',
      },
    }),
  ],
})
export class AppModule {}

创建服务

接下来,创建一个服务来发送邮件。你可以使用 @Injectable() 装饰器来定义这个服务,并注入 MailerService

import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';

@Injectable()
export class MailService {
  constructor(private readonly mailerService: MailerService) {}

  async sendUserWelcomeEmail() {
    await this.mailerService.sendMail({
      to: 'recipient@example.com', // 收件人地址
      subject: 'Welcome!', // 邮件主题
      template: 'welcome', // 模板名称
      context: {
        // 替换模板中的变量
        name: 'John Doe',
      },
    });
  }
}

创建邮件模板

nestjs-mailer 支持多种模板引擎,如 Pug、EJS 等。这里以 Pug 为例,创建一个 welcome.pug 文件:

h1 Welcome #{name}!
p Thank you for joining us.

确保你的模板文件位于 src/templates 目录下,或者你可以通过配置 MailerModule 来指定模板路径。

调用服务

最后,在控制器或其他服务中调用 MailService 中的方法来发送邮件。

import { Controller, Get } from '@nestjs/common';
import { MailService } from './mail.service';

@Controller('mail')
export class MailController {
  constructor(private readonly mailService: MailService) {}

  @Get('send-welcome')
  async sendWelcomeEmail() {
    await this.mailService.sendUserWelcomeEmail();
    return { message: 'Email sent successfully!' };
  }
}

这样,你就完成了一个基本的邮件发送功能。你可以根据需要调整配置和模板。


3 回复

当然,了解nestjs-mailer插件后,你会发现用Node.js和NestJS发送邮件就像吃巧克力一样简单(好吧,可能没那么好吃,但至少不难)!

首先,你需要安装@nestjs-modules/mailer。打开你的终端,像这样施展你的魔法:

npm install @nestjs-modules/mailer handlebars

接着,在你的模块文件中(比如app.module.ts),注入MailerModule,就像这样:

@Module({
  imports: [
    MailerModule.forRoot({
      transport: 'your-email-service-config-here',
      defaults: {
        from: '"nest-modules" <modules@nestjs.com>',
      },
      template: {
        dir: join(__dirname, 'templates'),
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
    }),
  ],
})
export class AppModule {}

别忘了替换your-email-service-config-here为你的邮件服务配置信息。

然后,在你的服务中,你可以愉快地发送邮件了:

@Injectable()
export class AppService {
  constructor(private readonly mailerService: MailerService) {}

  async sendUserWelcomeEmail() {
    this.mailerService.sendMail({
      to: 'test@example.com', // 目标邮箱
      subject: '欢迎来到我们的神奇世界!',
      template: 'welcome', // 模板名
      context: { // 上下文数据
        title: '欢迎!',
      },
    });
  }
}

最后,确保你的模板文件(例如welcome.hbs)位于你之前指定的目录中,比如src/templates/welcome.hbs

现在,你可以尽情享受用NestJS发送邮件的乐趣了!


nestjs-mailer 是一个基于 NestJS 框架的邮件发送库,它封装了 nodemailer 库,使得在 NestJS 项目中发送邮件变得简单。以下是如何在 NestJS 项目中安装和配置 nestjs-mailer 的步骤。

安装

首先,你需要在你的 NestJS 项目中安装 nestjs-mailer 和必要的依赖:

npm install @nestjs-modules/mailer nodemailer

配置

接下来,在你的 NestJS 应用中配置 MailerModule。通常情况下,你会在主模块(例如 AppModule)中进行配置。

import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        host: 'smtp.example.com',
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
          user: 'your-email@example.com', // generated ethereal user
          pass: 'your-email-password', // generated ethereal password
        },
      },
      defaults: {
        from: '"nest-modules" <modules@nestjs.com>',
      },
      template: {
        adapter: new HandlebarsAdapter(), // or new PugAdapter() for pug templates
        options: {
          strict: true,
        },
      },
    }),
  ],
})
export class AppModule {}

使用

现在你可以在任何服务或控制器中注入 MailerService 并使用它来发送邮件。

import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';

@Injectable()
export class AppService {
  constructor(private readonly mailerService: MailerService) {}

  async sendUserWelcomeEmail() {
    await this.mailerService.sendMail({
      to: 'test@example.com', // list of receivers
      from: '"nest-modules" <modules@nestjs.com>', // sender address
      subject: 'Welcome', // Subject line
      template: 'welcome', // The `.hbs` extension is appended automatically
      context: {
        // data for the template
        name: 'John Doe',
      },
    });
  }
}

在这个例子中,template 字段指定了要使用的模板名称,而 context 包含了模板中的变量数据。你可以创建 .hbs.pug 等模板文件,并在 MailerModule 中指定模板适配器。

希望这些信息对你有所帮助!如果你有任何进一步的问题,请随时提问。

NestJS 使用 nestjs-mailer 插件可以方便地集成 Mailer 来发送邮件。首先安装依赖:

npm install @ nestjsx / nestjs-mailer --save
npm install nodemailer --save

然后,在模块中导入 MailerModule 并配置 MailerOptions

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        host: 'smtp.yourserver.com',
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
          user: 'your-email@example.com',
          pass: 'your-password'
        }
      },
      defaults: {
        from: '"nest-modules" <modules@nestjs.com>',
      },
    }),
  ],
})
export class ApplicationModule {}

接着,可以在服务中注入 MailService 来发送邮件:

@Injectable()
export class AppService {
  constructor(private readonly mailService: MailService) {}

  async sendEmail() {
    await this.mailService.sendMail({
      to: 'recipient@example.com',
      subject: 'Hello',
      text: 'Hello to you!',
    });
  }
}

以上就是在 NestJS 中使用 nestjs-mailer 插件的基本步骤。

回到顶部