邮件服务
原创2026/3/5大约 1 分钟
邮件模板email.hbs
<html>
<head>
<meta charset='utf-8' />
<title>邮箱验证码</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f7f7f7;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: #ffffff;
border-radius: 8px;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.header {
text-align: center;
padding-bottom: 20px;
}
.title {
font-size: 24px;
font-weight: bold;
}
.content {
line-height: 1.6;
}
.footer {
text-align: center;
margin-top: 20px;
font-size: 12px;
color: #888;
}
.button {
display: inline-block;
background-color: #007bff;
color: #ffffff;
padding: 10px 20px;
text-decoration: none;
border-radius: 4px;
}
</style>
</head>
<body>
<div class='container'>
<div class='header'>
<div class='title'>验证码</div>
</div>
<div class='content'>
<p>尊敬的用户:</p>
<p>您的验证码为:<span
style='font-weight: 600;'
>{{code}}</span>,该验证码1分钟内有效,如非本人操纵,请忽略本邮件!</p>
<p>感谢您使用我们的服务!</p>
<a class='button' href='https://jiameikj.com'>嘉美工作室</a>
</div>
<div class='footer'>
<p>联系我们:486428167@qq.com</p>
<p>版权所有 © 2023 JIAMEI 保留所有权利。</p>
</div>
</div>
</body>
</html>安装
npm i --save @nestjs-modules/mailer nodemailer
npm install --save-dev @types/nodemailer配置
import { Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { MailerModule } from '@nestjs-modules/mailer'
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter'
@Module({
imports: [
MailerModule.forRoot({
transport: `smtps://486428167@qq.com:wxpjjgpsmwinbiaf@smtp.qq.com`,
defaults: {
from: '"nest-modules" <modules@nestjs.com>',
},
template: {
dir: 'src/views',
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}使用
import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { MailerService } from '@nestjs-modules/mailer'
@Injectable()
export class AppService {
constructor(private readonly mailerService: MailerService) {}
async v1() {
const email = '486428167@qq.com'
const code = '123456'
try {
await this.mailerService.sendMail({
to: email,
from: '486428167@qq.com',
subject: '验证码✔',
template: 'email',
context: {
code: code,
},
})
return {
code: 200,
msg: '邮件发送成功',
}
} catch (error) {
throw new HttpException('邮件发送失败', HttpStatus.BAD_REQUEST)
}
}
}至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。