①引入依赖:
npm i @nestjs-modules/mailer nodemailer
这里是引入相应的需要的依赖。
创建模块,以及服务
nest generate module sendEmail
nest generate service sendEmail
②在app.module中注册,之后在其它的模块就可以使用
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { PugAdapter } from '@nestjs-modules/mailer/dist/adapters/pug.adapter';
@Module({
imports: [
MailerModule.forRoot({
transport: {
host: process.env.EMAIL_HOST, // Replace with the SMTP server of the email provider
port: parseInt(process.env.EMAIL_PORT), // Typically 465 for secure SMTP (SSL/TLS)
secure: true, // Use SSL/TLS
auth: {
user: process.env.EMAIL_USERNAME, // Your email address
pass: process.env.EMAIL_PASSWORD, // Your email password
},
},
defaults: {
from: `"${process.env.EMAIL_FROM}" <${process.env.EMAIL_FROM_ADDRESS}>`, // Default sender address
},
template: {
dir: join(__dirname, 'templates'), // Directory for email templates
adapter: new PugAdapter(), // Template engine
options: {
strict: true,
},
},
}),
],
providers: [
],
exports: [],
})
export class AppModule {}
EMAIL_HOST='smtp.163.com'
EMAIL_PORT='465'
EMAIL_USERNAME='你的邮箱号'
EMAIL_PASSWORD='你的邮箱密码'
EMAIL_FROM='发送的来源信息'
EMAIL_FROM_ADDRESS='你的邮箱号'
到这里你就配置完成了信息
import { Module } from '@nestjs/common';
import { SendEmailService } from './send-email.service';
@Module({
providers: [SendEmailService],
exports: [SendEmailService],
})
export class SendEmailModule {}
③使用:
我这里将内容抽取出来作为方法来使用
import { MailerService } from '@nestjs-modules/mailer';
import { Injectable } from '@nestjs/common';
@Injectable()
export class SendEmailService {
constructor(private readonly mailerService: MailerService) {}
// eslint-disable-next-line max-lines-per-function
async sendEmail(
to: string,
subject: string,
title: string,
subTitle: string,
description: string,
content: string | number,
) {
const result = await this.mailerService.sendMail({
to,
from: process.env.EMAIL_FROM_ADDRESS,
subject: subject,
template: 'reset-password',
context: {
title,
subTitle,
description,
content,
},
});
return result;
}
}
这里的reset-password是模块的名称
就在该模块下的templates文件夹下创建reset-password.hbs内容
<html lang='en-US'>
<head>
<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
<title>${title}</title>
<meta name='description' content='Email Template' />
<style type='text/css'>
a:hover { text-decoration: underline !important; }
</style>
</head>
<body
marginheight='0'
topmargin='0'
marginwidth='0'
style='margin: 0px; background-color: #f2f3f8'
leftmargin='0'
>
<!--100% body table-->
<!-- 这里输入自己想要的样式,要发送的内容等-->
<!--/100% body table-->
</body>
</html>
这里就是发送的样式的路径位置,以及文件名称
这样就将整个发送的从注册到使用书写完成