如何在NestJS中轻松发送电子邮件?

高效发送电子邮件:使用@nestixis/nestjs-mailer简化流程

在许多应用中,发送电子邮件至关重要,无论是用户通知、事务更新还是营销活动。然而,传统的电子邮件解决方案往往复杂且繁琐,需要整合邮件程序、模板语言,并处理各种依赖关系。

解决方案:

@nestixis/nestjs-mailer包提供了一种简洁、灵活且可靠的方案,简化了电子邮件发送流程。它结合了React和Nodemailer的优势,让开发者能够轻松创建动态电子邮件模板并发送邮件。

步骤详解:

安装包:

使用npm安装:

npm install @nestixis/nestjs-mailer

模块配置:

在你的NestJS应用中配置mailersdkmodule。为了测试,可以使用MailCatch等工具捕获邮件,无需发送到真实邮箱。示例配置如下:

import { Mailersdkmodule } from '@nestixis/nestjs-mailer';import { Module } from '@nestjs/common';import { AppController } from './app.controller';import { AppService } from './app.service';@Module({  imports: [    Mailersdkmodule.register({      auth: {        user: 'username',        password: 'password',        host: 'sandbox-smtp.mailcatch.app',        port: 2525,        ssl: false,      },      from: 'your-email@example.com',    }),  ],  controllers: [AppController],  providers: [AppService],})export class AppModule {}

创建电子邮件模板:

为了创建美观的电子邮件,建议结合React和@react-email/components包。 在tsconfig.json文件中设置"jsx": "react"

以下是一个邀请新管理员的模板示例(invite-admin-with-account-template.tsx):

import { body, container, head, html, img, link, section, text } from '@react-email/components';import * as React from 'react';export default function InviteAdminWithAccountTemplate({ translation, language, invitationHref, passwordHref, logoUrl }) {  return (          {logoUrl ? @@##@@ : {translation.titleInside}}      {translation.contentPart1}      {translation.contentPart2}              {translation.contentPart3.subpart1}                {translation.contentPart3.subpart2}        {translation.contentPart3.subpart3}                    {translation.contentPart4.subpart1}                {translation.contentPart4.subpart2}            );}

注入电子邮件发送器:

将电子邮件发送器注入到你的服务中:

import { EmailSenderInterface, MAILER_SDK_CLIENT } from '@nestixis/nestjs-mailer';import { Inject, Injectable } from '@nestjs/common';import InviteAdminWithAccountTemplate from './invite-admin-with-account-template';@Injectable()export class AppService {  constructor(    @Inject(MAILER_SDK_CLIENT)    private readonly emailSender: EmailSenderInterface,  ) {}  async send(): Promise {    // ... (邮件内容和配置) ...    await this.emailSender.sendEmail(      'test@test.com',      'Admin Invitation',      emailContent,    );  }}

完成!

logo

现在,你已经成功集成了nestjs-mailer。更多细节和高级功能,请参考nestjs-mailer的GitHub仓库。

如何在NestJS中轻松发送电子邮件?

以上就是如何在NestJS中轻松发送电子邮件?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1500294.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
以 semver ‘0’ 开头
上一篇 2025年12月19日 22:30:48
从优秀到卓越:掌握前端开发
下一篇 2025年12月19日 22:31:01

相关推荐

发表回复

登录后才能评论
关注微信