Nodejs Nestjs邮件发送插件@nestjs/mail的使用

Nodejs Nestjs邮件发送插件@nestjs/mail的使用
[@nestjs](/user/nestjs)/mail 是一个用于 NestJS 应用程序的邮件发送库。但是,目前(2023年)还没有官方的 [@nestjs](/user/nestjs)/mail 包,不过你可以使用一些流行的邮件库,如 nodemailer 来实现邮件发送功能。

下面是一个使用 nodemailer 的示例,它是一个非常流行的 Node.js 邮件传输库:

  1. 安装 nodemailer 和其他必要的依赖:
npm install [@nestjs](/user/nestjs)/common [@nestjs](/user/nestjs)/core nodemailer
  1. 创建一个服务来处理邮件发送逻辑:
import { Injectable } from '[@nestjs](/user/nestjs)/common';
import * as nodemailer from 'nodemailer';

@Injectable()
export class MailService {
  private transporter: nodemailer.Transporter;

  constructor() {
    this.transporter = nodemailer.createTransport({
      host: 'smtp.example.com',
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: 'your-email@example.com', // your email
        pass: 'your-password', // your password
      },
    });
  }

  async sendEmail(to: string, subject: string, text: string) {
    const mailOptions = {
      from: 'your-email@example.com', // sender address
      to, // list of receivers
      subject, // Subject line
      text, // plain text body
    };

    return this.transporter.sendMail(mailOptions);
  }
}
  1. 在你的控制器中使用这个服务:
import { Controller, Get, Param } from '[@nestjs](/user/nestjs)/common';
import { MailService } from './mail.service';

@Controller('email')
export class EmailController {
  constructor(private readonly mailService: MailService) {}

  @Get(':to/:subject/:text')
  async send(@Param('to') to: string, @Param('subject') subject: string, @Param('text') text: string) {
    return this.mailService.sendEmail(to, subject, text);
  }
}
  1. 在你的模块文件中(例如 app.module.ts)导入并提供你的服务:
import { Module } from '[@nestjs](/user/nestjs)/common';
import { MailService } from './mail.service';
import { EmailController } from './email.controller';

@Module({
  imports: [],
  controllers: [EmailController],
  providers: [MailService],
})
export class AppModule {}

现在你可以在浏览器或 Postman 中通过访问 /email/to-address/subject/text-content 路径来测试邮件发送功能了。

注意:在实际部署时,建议不要将电子邮件账户的用户名和密码硬编码到代码中,而是使用环境变量来存储敏感信息。


3 回复

当然,要使用[@nestjs](/user/nestjs)/mail这个插件来发送邮件,首先你需要确保已经安装了它以及相应的邮件服务库(比如nodemailer)。这里有一个简单的步骤指南:

  1. 安装依赖:

    npm install [[@nestjs](/user/nestjs)-modules](/user/nestjs-modules)/mailer nodemailer
    
  2. 配置模块,在你的AppModule或其他模块中配置MailerModule:

    import { Module } from '[@nestjs](/user/nestjs)/common';
    import { MailerModule } from '[[@nestjs](/user/nestjs)-modules](/user/nestjs-modules)/mailer';
    
    [@Module](/user/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](/user/nestjs).com>',
          },
        }),
      ],
    })
    export class AppModule {}
    
  3. 在你的服务中注入MailService并使用它来发送邮件:

    import { Injectable } from '[@nestjs](/user/nestjs)/common';
    import { MailerService } from '[[@nestjs](/user/nestjs)-modules](/user/nestjs-modules)/mailer';
    
    [@Injectable](/user/Injectable)()
    export class AppService {
      constructor(private readonly mailerService: MailerService) {}
    
      async sendUserEmail() {
        this.mailerService.sendMail({
          to: 'recipient@example.com', // list of receivers
          subject: 'Sending with Transport', // Subject line
          template: 'path/to/template', // Optional path to pug template
          context: {
            // Data to be sent to template engine.
            name: 'John Doe',
          },
        });
      }
    }
    

记得替换SMTP服务器信息和认证详情为你自己的设置。希望这能帮到你!如果需要更详细的帮助,随时告诉我!


@nestjs/mail 是一个用于 NestJS 的邮件发送库,它基于 nodemailer。不过请注意,目前 GitHub 上并没有名为 @nestjs/mail 的官方包。你可以通过 @nestjs-modules/mailer 这个模块来实现邮件发送功能。

下面是一个简单的使用示例:

首先,你需要安装必要的依赖包:

npm install @nestjs-modules/mailer @nestjs/throttler nodemailer

然后在你的 NestJS 项目中配置 @nestjs-modules/mailer

  1. 修改 app.module.ts 文件:添加 MailModule 并配置 SMTP 服务。
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.yourserver.com', // SMTP 服务器地址
        port: 587, // SMTP 端口
        secure: false,
        auth: {
          user: 'your-email@example.com', // 邮箱账户
          pass: 'your-email-password', // 邮箱密码
        },
      },
      defaults: {
        from: '"nest-modules" <modules@nestjs.com>', // 默认发件人
      },
      template: {
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
    }),
  ],
})
export class AppModule {}
  1. 创建一个服务 来发送邮件
import { Injectable } from '@nestjs/common';
import { InjectMailer } from '@nestjs-modules/mailer';

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

  async sendUserWelcomeEmail() {
    await this.mailer.sendMail({
      to: 'target.email@example.com', // 目标邮箱
      subject: '欢迎注册', // 邮件主题
      template: './welcome', // 模板文件路径
      context: {
        // 替换模板中的变量
        name: 'John Doe',
      },
    });
  }
}
  1. 在控制器中调用服务
import { Controller, Get } from '@nestjs/common';
import { MailService } from './mail.service';

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

  @Get('send')
  async sendMail() {
    return await this.mailService.sendUserWelcomeEmail();
  }
}

确保你的 SMTP 服务器设置正确,并且你有权限访问该服务器。此外,如果你的邮件内容复杂,建议使用模板引擎(如 Handlebars)来构建邮件内容。

@nestjs-mail 并不是官方或广泛使用的插件名称,可能您指的是 nest-email 或其他类似的库。通常使用 nodemailer 作为底层库来实现邮件发送功能。

例如,你可以使用 nest-email 这个库:

  1. 安装依赖:

    npm install nest-email nodemailer
    
  2. 在你的 NestJS 模块中配置:

    import { EmailModule } from 'nest-email';
    
    [@Module](/user/Module)({
      imports: [
        EmailModule.forRoot({
          transport: {
            host: 'smtp.example.com',
            port: 587,
            secure: false, // true for 465, false for other ports
            auth: {
              user: 'user@example.com', 
              pass: 'yourpassword'
            }
          },
        }),
      ],
    })
    export class AppModule {}
    
  3. 使用服务发送邮件:

    import { EmailService } from 'nest-email';
    
    [@Injectable](/user/Injectable)()
    export class AppService {
      constructor(private readonly emailService: EmailService) {}
    
      async sendMail() {
        await this.emailService.sendMail({
          to: 'recipient@example.com',
          subject: 'Hello',
          text: 'This is a test email.',
        });
      }
    }
    

请根据实际使用的库进行相应调整。

回到顶部