@builder6/email
v4.0.0
Published
Builder6 Email 模块为 Builder6 平台提供完整的邮件发送和队列管理功能,支持 SMTP 邮件发送、邮件队列处理、批量发送等企业级邮件服务。
Downloads
1,713
Keywords
Readme
Builder6 Email Module
Builder6 Email 模块为 Builder6 平台提供完整的邮件发送和队列管理功能,支持 SMTP 邮件发送、邮件队列处理、批量发送等企业级邮件服务。
功能特性
- SMTP 邮件发送: 支持标准 SMTP 协议发送邮件
- 邮件队列: 基于数据库的邮件队列,支持失败重试
- 批量发送: 支持批量邮件发送,可配置批次大小
- 定时发送: 自动定时检查队列并发送待发邮件
- 邮件模板: 支持 HTML 和文本邮件模板
- 附件支持: 支持邮件附件发送
- 邮件验证: 自动验证邮件地址格式
- 发送日志: 记录邮件发送状态和日志
- 失败处理: 发送失败自动重试机制
- 队列保留: 可选择发送后保留或删除队列记录
安装
npm install @builder6/email或
yarn add @builder6/email环境变量
SMTP 服务器配置
# 启用邮件服务
B6_EMAIL_ENABLED=true
# 发件人地址
B6_EMAIL_FROM=Steedos <[email protected]>
# SMTP 服务器地址
B6_EMAIL_HOST=email.example.amazonaws.com
# SMTP 服务器端口
B6_EMAIL_PORT=465
# SMTP 用户名
B6_EMAIL_USERNAME=your-smtp-username
# SMTP 密码
B6_EMAIL_PASSWORD=your-smtp-password
# 使用 SSL/TLS
B6_EMAIL_SECURE=true
# 启用调试模式
B6_EMAIL_DEBUG=false
# 启用日志记录
B6_EMAIL_LOGGER=true邮件队列配置
当 B6_EMAIL_ENABLED=true 时,系统会启动定时任务从 _mail_queue 集合中读取邮件并发送。
# 邮件队列检查间隔(毫秒),默认 3000ms = 3秒
STEEDOS_EMAIL_QUEUE_INTERVAL=3000
# 每次批量发送的邮件数量,默认 1
STEEDOS_EMAIL_QUEUE_BATCH_SIZE=10
# 邮件发送超时时间(毫秒),默认 60000ms = 60秒
STEEDOS_EMAIL_QUEUE_TIMEOUT=60000
# 邮件发送后是否保留队列记录,默认 false(删除)
STEEDOS_EMAIL_QUEUE_KEEPS=false常用 SMTP 提供商配置
Gmail
B6_EMAIL_HOST=smtp.gmail.com
B6_EMAIL_PORT=465
B6_EMAIL_SECURE=true
[email protected]
B6_EMAIL_PASSWORD=your-app-passwordAmazon SES
B6_EMAIL_HOST=email-smtp.us-east-1.amazonaws.com
B6_EMAIL_PORT=465
B6_EMAIL_SECURE=true
B6_EMAIL_USERNAME=your-smtp-username
B6_EMAIL_PASSWORD=your-smtp-passwordOutlook/Office 365
B6_EMAIL_HOST=smtp.office365.com
B6_EMAIL_PORT=587
B6_EMAIL_SECURE=false
[email protected]
B6_EMAIL_PASSWORD=your-password腾讯企业邮箱
B6_EMAIL_HOST=smtp.exmail.qq.com
B6_EMAIL_PORT=465
B6_EMAIL_SECURE=true
[email protected]
B6_EMAIL_PASSWORD=your-password使用示例
在 NestJS 应用中集成
import { Module } from '@nestjs/common';
import { EmailModule } from '@builder6/email';
@Module({
imports: [EmailModule],
})
export class AppModule {}使用 EmailService 发送邮件
import { EmailService } from '@builder6/email';
constructor(private emailService: EmailService) {}
// 发送简单文本邮件
async sendTextEmail() {
await this.emailService.send({
to: '[email protected]',
subject: 'Welcome to Builder6',
text: 'Thank you for joining us!'
});
}
// 发送 HTML 邮件
async sendHtmlEmail() {
await this.emailService.send({
to: '[email protected]',
subject: 'Welcome to Builder6',
html: '<h1>Welcome!</h1><p>Thank you for joining us!</p>'
});
}
// 发送带附件的邮件
async sendEmailWithAttachment() {
await this.emailService.send({
to: '[email protected]',
subject: 'Document Attached',
html: '<p>Please find the document attached.</p>',
attachments: [
{
filename: 'document.pdf',
path: '/path/to/document.pdf'
}
]
});
}
// 发送给多个收件人
async sendToMultipleRecipients() {
await this.emailService.send({
to: ['[email protected]', '[email protected]'],
cc: ['[email protected]'],
bcc: ['[email protected]'],
subject: 'Team Update',
html: '<p>Important team update...</p>'
});
}使用邮件队列
import { EmailQueueService } from '@builder6/email';
constructor(private emailQueueService: EmailQueueService) {}
// 添加邮件到队列
async queueEmail() {
await this.emailQueueService.addToQueue({
to: '[email protected]',
subject: 'Queued Email',
html: '<p>This email will be sent by the queue processor.</p>',
priority: 1, // 优先级,数字越小优先级越高
scheduledAt: new Date('2024-01-20 10:00:00') // 计划发送时间
});
}
// 批量添加邮件到队列
async queueBatchEmails(users: User[]) {
const emails = users.map(user => ({
to: user.email,
subject: 'Newsletter',
html: `<p>Hello ${user.name},</p><p>Your monthly newsletter...</p>`
}));
await this.emailQueueService.addBatchToQueue(emails);
}
// 获取队列状态
async getQueueStatus() {
const pending = await this.emailQueueService.getPendingCount();
const failed = await this.emailQueueService.getFailedCount();
return { pending, failed };
}
// 重试失败的邮件
async retryFailedEmails() {
await this.emailQueueService.retryFailed();
}邮件队列数据结构
邮件队列存储在 MongoDB 的 _mail_queue 集合中:
interface MailQueue {
_id: string;
to: string | string[];
cc?: string | string[];
bcc?: string | string[];
from?: string;
subject: string;
text?: string;
html?: string;
attachments?: Array<{
filename: string;
path?: string;
content?: Buffer;
}>;
status: 'pending' | 'sending' | 'sent' | 'failed';
priority: number; // 1-10,数字越小优先级越高
attempts: number; // 发送尝试次数
lastAttempt?: Date;
scheduledAt?: Date; // 计划发送时间
sentAt?: Date;
error?: string;
created: Date;
modified: Date;
}邮件模板
使用 LiquidJS 模板
import { EmailService } from '@builder6/email';
async sendTemplatedEmail(user: User) {
const template = `
<h1>Welcome, {{ user.name }}!</h1>
<p>Your account has been created successfully.</p>
<p>Username: {{ user.username }}</p>
<p>Email: {{ user.email }}</p>
`;
const html = this.emailService.renderTemplate(template, { user });
await this.emailService.send({
to: user.email,
subject: 'Welcome to Builder6',
html
});
}API 端点
模块提供以下主要 API 端点(如果启用 HTTP 接口):
- POST
/api/v6/email/send: 直接发送邮件(需要管理员权限) - POST
/api/v6/email/queue: 添加邮件到队列 - GET
/api/v6/email/queue/status: 获取队列状态 - POST
/api/v6/email/queue/retry: 重试失败的邮件
邮件队列处理流程
- 添加到队列: 邮件信息写入
_mail_queue集合,状态为pending - 定时检查: 每隔
STEEDOS_EMAIL_QUEUE_INTERVAL毫秒检查一次队列 - 批量处理: 按优先级和创建时间排序,每次处理
STEEDOS_EMAIL_QUEUE_BATCH_SIZE条 - 发送邮件: 更新状态为
sending,调用 SMTP 发送 - 更新状态:
- 成功:更新为
sent,记录发送时间 - 失败:更新为
failed,记录错误信息,增加尝试次数
- 成功:更新为
- 清理队列: 如果
STEEDOS_EMAIL_QUEUE_KEEPS=false,删除已发送的邮件
失败重试策略
- 默认最大重试次数:3 次
- 重试间隔:指数退避(exponential backoff)
- 第 1 次失败:等待 1 分钟
- 第 2 次失败:等待 5 分钟
- 第 3 次失败:等待 15 分钟
- 超过最大重试次数后,邮件保持
failed状态,需要手动处理
性能优化
批量发送优化
# 增加批量大小以提高吞吐量
STEEDOS_EMAIL_QUEUE_BATCH_SIZE=50
# 减少检查间隔以更快处理队列
STEEDOS_EMAIL_QUEUE_INTERVAL=1000连接池优化
# 配置 SMTP 连接池
B6_EMAIL_POOL=true
B6_EMAIL_POOL_MAX_CONNECTIONS=10
B6_EMAIL_POOL_MAX_MESSAGES=100监控和日志
启用详细日志
B6_EMAIL_DEBUG=true
B6_EMAIL_LOGGER=true日志信息包括
- SMTP 连接状态
- 邮件发送详情
- 错误和异常信息
- 队列处理统计
使用场景
- 用户通知: 注册欢迎邮件、密码重置、系统通知
- 营销邮件: 新闻通讯、产品更新、促销活动
- 交易邮件: 订单确认、发货通知、发票
- 报告邮件: 定期生成并发送统计报告
- 警报邮件: 系统异常、安全警告、监控告警
- 工作流通知: 审批通知、任务提醒、到期提醒
安全注意事项
- 凭据保护: 使用环境变量存储 SMTP 凭据,不要硬编码
- 邮件验证: 验证收件人邮箱地址格式,防止发送到无效地址
- 速率限制: 遵守 SMTP 提供商的发送速率限制
- SPF/DKIM: 配置 SPF 和 DKIM 记录提高邮件送达率
- 退订链接: 营销邮件应包含退订链接
- 敏感信息: 避免在邮件中传输敏感信息,使用加密链接
依赖项
主要依赖
nodemailer: ^7.0.11 - 邮件发送库email-addresses: ^5.0.0 - 邮件地址解析和验证bluebird: ^3.7.2 - Promise 增强库lodash: ^4.17.21 - 工具函数库
Peer Dependencies
@builder6/core: ^3.0.10 - 核心功能模块@builder6/moleculer: ^3.0.10 - 微服务框架@nestjs/common: ^11.0.0 - NestJS 核心@nestjs/core: ^11.0.0 - NestJS 核心@nestjs/swagger: ^11.0.7 - API 文档
开发
构建
npm run build监听模式
npm run build:watch格式化代码
npm run format故障排查
常见问题
- 邮件发送失败: 检查 SMTP 配置和网络连接
- 认证失败: 验证用户名和密码是否正确
- 被拒绝发送: 检查是否超过了发送限制
- 邮件进入垃圾箱: 配置 SPF、DKIM 和 DMARC 记录
- 队列积压: 增加批量大小或减少检查间隔
License
MIT
