基于Nest.js(Typescript)+Mongodb+TS定时任务实现发送邮件功能(qq邮箱)

基于Nest.js(Typescript)+Mongodb+TS定时任务实现发送邮件功能(qq邮箱)

一、背景与问题

在现代Web应用中,邮件通知功能是常见的业务需求。例如用户注册后发送验证邮件、订单支付成功后发送通知邮件等场景。传统做法是通过同步方式调用邮件服务,但存在以下问题:

  1. 同步调用阻塞:在高并发场景下,邮件发送可能成为性能瓶颈
  2. 可靠性不足:网络波动或服务异常可能导致邮件丢失
  3. 资源浪费:每次请求都建立SMTP连接会消耗大量资源
  4. 调度困难:定时任务需要复杂的时间管理机制

本方案通过Nest.js的定时任务功能,结合MongoDB存储邮件记录,实现异步、可靠的邮件发送系统。特别适用于需要定时处理邮件发送、需要记录发送状态、需要处理邮件重试等场景。

二、基本原理

整个系统分为三个核心模块:

  1. 邮件接收模块:接收用户请求,存储邮件记录到MongoDB
  2. 定时任务模块:定时从MongoDB中获取待发送邮件
  3. 邮件发送模块:通过SMTP协议发送邮件,并记录发送结果

关键原理包括:

  • 异步处理:通过队列机制解耦邮件接收和发送过程
  • 持久化存储:使用MongoDB记录邮件状态,防止数据丢失
  • 重试机制:支持发送失败后的自动重试
  • 定时调度:使用CronJob模块实现精确的定时任务

三、环境准备

1. 技术栈

  • Nest.js(基于TypeScript)
  • MongoDB
  • nodemailer(邮件发送)
  • cron(定时任务)
  • dotenv(环境变量管理)

2. 依赖安装

npm install @nestjs/cron @nestjs/common @nestjs/core mongoose dotenv nodemailer

3. 环境配置

创建.env文件:

MONGO_URI=mongodb://localhost:27017/email_service
SMTP_HOST=smtp.qq.com
SMTP_PORT=465
SMTP_USER=your@qq.com
SMTP_PASS=your_authorization_code

四、核心实现

1. 邮件接收接口

// src/email/email.controller.ts
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { EmailService } from './email.service';
import { EmailRequest } from './dto/email.request';

@Controller('email')
export class EmailController {
  constructor(private readonly emailService: EmailService) {}

  @Post('send')
  @HttpCode(HttpStatus.CREATED)
  async sendEmail(@Body() request: EmailRequest) {
    const result = await this.emailService.saveEmail({
      ...request,
      status: 'pending',
      createdAt: new Date()
    });
    return { id: result._id };
  }
}

关键点说明:

  • 使用HttpCode保证接口返回201状态码
  • 邮件内容存储为pending状态
  • 返回邮件ID用于后续查询

2. 邮件发送服务

// src/email/email.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { EmailDocument, Email } from './schema/email.schema';
import { EmailRequest } from './dto/email.request';
import { Cron, CronExpression } from '@nestjs/schedule';
import { MailOptions, Transporter } from 'nodemailer';

@Injectable()
export class EmailService {
  private transporter: Transporter;

  constructor(
    @InjectModel(Email.name) private emailModel: Model<EmailDocument>
  ) {
    this.transporter = this.createTransporter();
  }

  private createTransporter(): Transporter {
    return nodemailer.createTransport({
      service: 'qq',
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS
      }
    });
  }

  @Cron(CronExpression.EVERY_5_MINUTES)
  async sendPendingEmails() {
    const emails = await this.emailModel.find({ status: 'pending' }).limit(10);
    for (const email of emails) {
      try {
        await this.sendEmail(email);
        await this.emailModel.findByIdAndUpdate(email._id, { status: 'sent' });
      } catch (error) {
        await this.emailModel.findByIdAndUpdate(email._id, { status: 'failed' });
        console.error(`Failed to send email to ${email.to}`, error);
      }
    }
  }

  async sendEmail(email: Email) {
    const mailOptions: MailOptions = {
      from: process.env.SMTP_USER,
      to: email.to,
      subject: email.subject,
      html: email.html
    };
    await this.transporter.sendMail(mailOptions);
  }
}

关键点说明:

  • 使用@Cron装饰器创建定时任务
  • 每次处理最多10封邮件(防止资源耗尽)
  • 错误处理机制确保发送失败的邮件状态更新
  • 使用nodemailer的sendMail方法发送邮件

3. 邮件存储模型

// src/email/schemas/email.schema.ts
import { Schema, Document, Types } from 'mongoose';

export interface EmailDocument extends Document {
  _id: Types.ObjectId;
  to: string;
  subject: string;
  html: string;
  status: 'pending' | 'sent' | 'failed';
  createdAt: Date;
}

const EmailSchema = new Schema({
  to: { type: String, required: true },
  subject: { type: String, required: true },
  html: { type: String, required: true },
  status: { type: String, enum: ['pending', 'sent', 'failed'], default: 'pending' },
  createdAt: { type: Date, default: Date.now }
});

export default EmailSchema;

关键点说明:

  • 使用MongoDB的enum类型限制状态值
  • 添加createdAt字段用于时间排序
  • 使用default设置默认值

五、完整案例

1. 邮件发送接口测试

创建test-email接口用于测试:

// src/email/email.controller.ts
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { EmailService } from './email.service';
import { EmailRequest } from './dto/email.request';

@Controller('email')
export class EmailController {
  constructor(private readonly emailService: EmailService) {}

  @Post('send')
  @HttpCode(HttpStatus.CREATED)
  async sendEmail(@Body() request: EmailRequest) {
    const result = await this.emailService.saveEmail({
      ...request,
      status: 'pending',
      createdAt: new Date()
    });
    return { id: result._id };
  }

  @Post('test')
  @HttpCode(HttpStatus.CREATED)
  async testEmail() {
    const email = {
      to: 'test@qq.com',
      subject: 'Test Email',
      html: '<h1>This is a test email</h1>'
    };
    await this.emailService.saveEmail(email);
    return { message: 'Test email saved' };
  }
}

2. 定时任务日志记录

在定时任务中添加日志记录:

@Cron(CronExpression.EVERY_5_MINUTES)
async sendPendingEmails() {
  const now = new Date();
  const logs = [];
  
  const emails = await this.emailModel.find({ status: 'pending' }).limit(10);
  for (const email of emails) {
    try {
      await this.sendEmail(email);
      await this.emailModel.findByIdAndUpdate(email._id, { status: 'sent' });
      logs.push({
        timestamp: now,
        emailId: email._id,
        status: 'success',
        message: 'Email sent successfully'
      });
    } catch (error) {
      await this.emailModel.findByIdAndUpdate(email._id, { status: 'failed' });
      logs.push({
        timestamp: now,
        emailId: email._id,
        status: 'error',
        message: 'Failed to send email',
        error: error.message
      });
    }
  }

  // 将日志保存到MongoDB
  await this.emailModel.create(logs);
}

3. 邮件状态查询接口

// src/email/email.controller.ts
import { Controller, Get, Query, HttpCode, HttpStatus } from '@nestjs/common';
import { EmailService } from './email.service';

@Controller('email')
export class EmailController {
  constructor(private readonly emailService: EmailService) {}

  @Get('status')
  @HttpCode(HttpStatus.OK)
  async getEmailStatus(@Query('id') id: string) {
    const email = await this.emailService.getEmailById(id);
    return email;
  }
}

六、源码解析

1. 定时任务调度机制

@Cron装饰器底层使用node-schedule库实现,其核心原理是:

  • 基于时间间隔的事件驱动机制
  • 使用线程池处理任务队列
  • 支持多种调度表达式(如CronExpression.EVERY_5_MINUTES)

2. 邮件发送流程

graph TD
    A[用户请求发送邮件] --> B[保存邮件记录到MongoDB]
    B --> C{是否定时发送?}
    C -->|是| D[定时任务触发]
    C -->|否| E[立即发送]
    D --> F[从MongoDB获取待发送邮件]
    F --> G[发送邮件]
    G --> H{发送成功?}
    H -->|是| I[更新邮件状态为"sent"]
    H -->|否| J[更新邮件状态为"failed"]

3. 错误处理机制

  • 使用try-catch块捕获异常
  • 邮件状态更新为失败
  • 记录错误日志
  • 可扩展重试机制(如使用retry-axios)

七、进阶使用

1. 重试机制实现

// src/email/email.service.ts
async sendEmail(email: Email, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      await this.transporter.sendMail({
        ...email,
        subject: `(${i + 1}) ${email.subject}`
      });
      await this.emailModel.findByIdAndUpdate(email._id, { status: 'sent' });
      return;
    } catch (error) {
      await this.emailModel.findByIdAndUpdate(email._id, { 
        status: 'failed', 
        retryCount: (email.retryCount || 0) + 1 
      });
      console.error(`Attempt ${i + 1} failed: ${error.message}`);
      await new Promise(resolve => setTimeout(resolve, 5000 * (i + 1)));
    }
  }
}

2. 邮件模板系统

// src/email/email.service.ts
async sendEmailWithTemplate(email: Email, template: string, data: any) {
  const rendered = await this.renderTemplate(template, data);
  await this.sendEmail({
    ...email,
    html: rendered,
    subject: `${email.subject} - Template ${template}`
  });
}

private async renderTemplate(template: string, data: any) {
  // 使用Handlebars或EJS模板引擎渲染
  return await this.templateEngine.render(template, data);
}

3. 邮件分类处理

// src/email/email.service.ts
async sendEmailWithCategory(email: Email, category: string) {
  const categoryConfig = await this.configService.getCategoryConfig(category);
  const finalEmail = {
    ...email,
    subject: `${categoryConfig.prefix} ${email.subject}`,
    html: `${categoryConfig.header}${email.html}${categoryConfig.footer}`
  };
  await this.sendEmail(finalEmail);
}

八、性能与工程实践

1. 性能优化策略

优化措施说明
连接池配置配置SMTP连接池大小(默认10)
批处理发送每次处理最多10封邮件
缓存模板使用Redis缓存模板内容
分页处理限制每次查询的邮件数量
异步处理使用队列系统(如RabbitMQ)

2. 异常处理机制

  • 使用try-catch捕获异常
  • 邮件状态更新为失败
  • 记录错误日志
  • 可扩展重试机制

3. 安全实践

  1. 敏感信息保护:使用.env文件存储SMTP凭证
  2. 输入验证:使用class-validator校验邮件参数
  3. XSS防护:对邮件内容进行HTML转义
  4. 日志安全:避免记录敏感信息到日志

4. 高可用方案

  • 使用MongoDB副本集保证数据可靠性
  • 部署多个Nest.js实例并使用Redis共享队列
  • 配置负载均衡器
  • 使用云服务的自动扩展功能

九、常见问题与踩坑

1. 常见错误及解决方案

错误类型现象原因解决方案
10002SMTP身份验证失败SMTP配置错误检查QQ邮箱SMTP设置
429请求过多频繁发送邮件增加定时任务间隔
550邮件服务器拒绝邮件内容不符合规范检查邮件内容格式
500内部服务器错误代码逻辑错误检查日志输出
11003邮件内容过大邮件内容超出限制简化邮件内容

2. 高级问题

  • 邮件发送延迟:检查定时任务调度策略
  • 邮件丢失:检查MongoDB的持久化配置
  • 资源耗尽:限制每次处理的邮件数量
  • 安全漏洞:防止邮件内容被恶意篡改

十、最佳实践

1. 推荐方案

  • 定时任务:使用@nestjs/schedule的@Cron装饰器
  • 邮件存储:使用MongoDB的文档模型存储
  • 邮件发送:使用nodemailer的SMTP协议
  • 错误处理:实现重试机制和日志记录
  • 扩展性:设计可扩展的邮件模板系统

2. 使用场景建议

场景是否适用原因
定时发送通知✅适合需要定时处理的场景
高并发邮件发送✅通过队列机制保证可靠性
邮件内容需要模板✅支持动态内容生成
需要记录发送状态✅自动记录邮件状态
需要重试机制✅内置重试机制
需要快速开发✅简化开发流程

3. 不适用场景

场景是否适用原因
实时邮件发送❌无法保证实时性
需要复杂路由规则❌不支持复杂的路由逻辑
需要处理大量附件❌需要额外处理附件
需要集成第三方邮件服务商❌需要额外配置

十一、总结

本方案通过Nest.js的定时任务功能,结合MongoDB的持久化存储,实现了可靠的邮件发送系统。关键点包括:

  1. 异步处理:通过队列机制解耦邮件接收和发送
  2. 持久化存储:确保邮件状态不会丢失
  3. 重试机制:处理发送失败的情况
  4. 定时调度:精确控制发送时间
  5. 安全防护:防止敏感信息泄露

适用场景包括定时通知、邮件验证、订单通知等场景,不适用需要实时响应或复杂路由规则的场景。开发过程中需要注意SMTP配置、错误处理和性能优化,确保系统的稳定性和可靠性。通过合理的设计,可以构建一个可扩展、可维护的邮件发送系统。

评论已关闭

推荐阅读

AIGC实战——Transformer模型
2024年12月01日
Socket TCP 和 UDP 编程基础(Python)
2024年11月30日
python , tcp , udp
如何使用 ChatGPT 进行学术润色?你需要这些指令
2024年12月01日
AI
最新 Python 调用 OpenAi 详细教程实现问答、图像合成、图像理解、语音合成、语音识别(详细教程)
2024年11月24日
ChatGPT 和 DALL·E 2 配合生成故事绘本
2024年12月01日
omegaconf,一个超强的 Python 库!
2024年11月24日
【视觉AIGC识别】误差特征、人脸伪造检测、其他类型假图检测
2024年12月01日
[超级详细]如何在深度学习训练模型过程中使用 GPU 加速
2024年11月29日
Python 物理引擎pymunk最完整教程
2024年11月27日
MediaPipe 人体姿态与手指关键点检测教程
2024年11月27日
深入了解 Taipy:Python 打造 Web 应用的全面教程
2024年11月26日
基于Transformer的时间序列预测模型
2024年11月25日
Python在金融大数据分析中的AI应用(股价分析、量化交易)实战
2024年11月25日
AIGC Gradio系列学习教程之Components
2024年12月01日
Python3 `asyncio` — 异步 I/O,事件循环和并发工具
2024年11月30日
llama-factory SFT系列教程:大模型在自定义数据集 LoRA 训练与部署
2024年12月01日
Python 多线程和多进程用法
2024年11月24日
Python socket详解,全网最全教程
2024年11月27日
python之plot()和subplot()画图
2024年11月26日
理解 DALL·E 2、Stable Diffusion 和 Midjourney 工作原理
2024年12月01日