发送电子邮件是许多应用程序中的一项关键功能,无论是用于用户通知、事务更新还是营销目的。然而,实施电子邮件解决方案有时可能很麻烦,因为您必须将邮件程序与模板语言集成,检查依赖关系......
但是!
使用 @nestixis/nestjs-mailer 包,您可以简化此过程,同时确保灵活性和可靠性。
这个包利用了 React 和 Nodemailer 的强大功能,使其成为一个现代且对开发人员友好的工具,可以轻松构建动态电子邮件模板并发送电子邮件。
让我们深入了解如何设置和使用它:)
首先,您需要在 NestJS 应用程序中安装 Nestjs-mailer 包。该软件包可通过 npm 获得,使安装快速而简单。在终端中运行以下命令:
npm install @nestixis/nestjs-mailer
安装软件包后,下一步是在您的应用程序中配置 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 结合使用,而 package@react-email/components 允许您设计此类电子邮件模板。
但在此之前,您应该调用文件 inform-admin-with-account-template.tsx 并设置
“jsx”:“反应”
在你的 tsconfig.json
以下是邀请新管理员用户的模板示例:
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 ( <Html lang={language}> <Head> <style>{/* Your custom styles here */}</style> </Head> <Body> <hr> <h2> Injecting the Email Sender </h2> <p>After creating your email template, the next step is to send the email. To do this, you inject the email sender into your service.<br> </p> <pre class="brush:php;toolbar:false">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<void> { const translations = { titleInside: { subpart1: 'Welcome', subpart2: ' to the platform!' }, contentPart1: 'Hello', contentPart2: 'Your admin account has been created.', contentPart3: { subpart1: 'Click here to activate your account: ', subpart2: 'Activate', subpart3: '.', }, contentPart4: { subpart1: 'To set your password, click here: ', subpart2: 'Set password', }, }; const emailContent = await InviteAdminWithAccountTemplate({ translation: translations, language: 'en', invitationHref: 'xxx', passwordHref: 'xxx', logoUrl: 'logo.png', }); await this.emailSender.sendEmail( 'test@test.com', 'Admin Invitation', emailContent, ); } }
就是这样!您已成功将 Nestjs-mailer 集成到您的应用程序中。
有关更多详细信息和高级功能,请查看 NestJS 邮件程序 GitHub 存储库。
以上是如何在NestJS中轻松发送电子邮件?的详细内容。更多信息请关注PHP中文网其他相关文章!