邮件发送(Mail)
基于异步 SMTP 连接池(rustls + ring)的通用邮件发送插件。提供纯文本与 HTML 正文、MiniJinja 模板渲染、内存或对象存储流式附件、内联 CID 图片、严格 CRLF Header 注入防护、非回环地址防明文降级护栏、CallFailure 重试分级、全套 Prometheus 指标,以及零网络的测试替身 MailFake。与 NotifyPlugin 联用时可直接启用内置的 SmtpChannel 走 Outbox 事务可靠投递。
快速接入#
在 Cargo.toml 开启主包 kxed 的 mail 特性(按需一并开启 templates 渲染 HTML 模板、object-store 发送对象存储附件,或 notify 接入 Outbox 异步投递):
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["mail", "templates", "object-store"] }在配置文件声明 SMTP 服务器与默认发件人(mail.password 属于 SecretString,建议经环境变量 KXED__MAIL__PASSWORD 或加密配置文件注入):
[mail]
smtp_host = "smtp.example.com"
smtp_port = 587
username = "mailer@example.com"
from_address = "noreply@example.com"
from_name = "Acme System"
tls_mode = "starttls"在应用入口注册 MailPlugin::new(),业务代码中通过 ctx.mailer()? 取得绑定当前请求/任务剩余期限的 Mailer 句柄发送邮件:
use kxed::plugins::mail::{MailAttachment, MailMessage, MailPlugin};
use kxed::prelude::*;
#[mutation(name = "reports.email", post = "/api/reports/email")]
pub async fn send_report_email(ctx: &AppCtx, to: String) -> Result<usize, AppErr> {
let message = MailMessage::new()
.to(to)
.subject("月度对账单")
.text("请查收附件中的月度对账单。")
.html_template("mail/monthly_report.html", serde_json::json!({ "month": "2026-11" }))
.attachment(MailAttachment::from_object_store(
None,
"reports/2026-11.pdf",
"monthly-report.pdf",
"application/pdf",
));
let receipt = ctx.mailer()?.send(message).await?;
Ok(receipt.recipient_count())
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.plugin(MailPlugin::new())
.run()
.await
}核心用法#
构造邮件与安全校验#
MailMessage 采用声明式链式构造,发送前及调用 message.validate() 时均会强制执行邮箱格式、CRLF/控制字符注入拦截、收件人总数与附件体积上限检查:
- 地址与展示名:支持
.from(...)/.named_from(name, addr)、.to(...)/.extend_to(...)、.cc(...)、.bcc(...)、.reply_to(...);也可用MailAddress::parse("Name <user@example.com>")预先校验。未显式设置发件人时自动回落到mail.from_address或MailPlugin::with_default_from(...)。 - 正文与模板:可设置
.text(...)、.html(...)或(开启templates且注册TemplatesPlugin时).html_template(name, context);同时提供纯文本与 HTML 时自动编码为multipart/alternative。 - 幂等键与扩展头:
.message_id("<id@example.com>")便于至少一次投递重发时由收件端去重;.header(name, value)添加自定义扩展头(如X-Correlation-Id),禁止覆写From、To、Subject、MIME-Version等保留头。
附件与内联资源#
| 构造方式 | 适用场景与行为 |
|---|---|
MailAttachment::bytes(filename, content_type, data) | 内存中的小型附件;校验文件名不含路径分隔符与双引号 |
MailAttachment::from_object_store(disk, key, filename, content_type) | 开启 object-store 且注册 ObjectStorePlugin 后可用;发送时分块流式拉取并实时检查累计体积不超过 mail.max_attachment_bytes |
.inline_cid(cid) | 标记为内联资源,供 HTML 正文通过 <img src="cid:logo@example.com"> 引用 |
传输安全与截止时刻控制#
- 防明文降级护栏(fail-closed):
mail.tls_mode默认为starttls(强制升级 STARTTLS,拒绝降级);implicit用于 465 端口 SMTPS;设为none仅允许回环地址(127.0.0.1、::1、localhost),向非回环地址使用明文必须显式设置mail.allow_insecure_plaintext = true,否则启动配置检查直接失败。 - 期限继承与启动探测:
ctx.mailer()?返回的句柄自动继承AppCtx::deadline(),与mail.send_timeout(或send_for(msg, timeout))取更短者作为总预算,防止慢 SMTP 拖垮请求线程;开启mail.verify_on_startup = true或调用MailPlugin::with_verify_on_startup(true)时,服务ready阶段会向 SMTP 服务端发起一次NOOP连通性检查,优雅退出时自动关闭连接池。
与 NotifyPlugin 协同投递#
需要业务写库与发邮件保持事务原子性、支持崩溃恢复、指数退避重试与死信重放时,不要在 HTTP 请求内同步等待 SMTP,而是将内置的 SmtpChannel 注册到 NotifyPlugin,详细用法见 通知插件的邮件通道。
测试替身 MailFake#
单元测试与集成测试中通过 MailPlugin::fake(fake.clone()) 或 Mailer::fake(&fake) 拦截全部出站邮件,无需启动真实 SMTP 服务器;即使在 Fake 模式下,引擎仍会执行完整的 MIME 编码、地址格式与附件大小校验,保证测试不漏掉非法报文:
use kxed::plugins::mail::{MailError, MailFake, MailPlugin};
use kxed::prelude::*;
async fn test_welcome_email() -> kxed::Result<()> {
let fake = MailFake::new();
let app = App::new()
.plugin(MailPlugin::fake(fake.clone()).with_default_from("noreply@example.com"))
.test()
.await?;
// 触发业务发信后直接断言捕获结果
fake.assert_sent_count(1);
fake.assert_sent_to("alice@example.com");
fake.assert_sent(|mail| mail.subject().contains("欢迎") && mail.attachments().len() == 1);
// 注入下一次投递失败,验证重试或错误分类
fake.fail_next(MailError::Transient {
status: Some(421),
reason: "try again later".into(),
});
Ok(())
}配置#
| 键 | 缺省 | 范围与含义 |
|---|---|---|
mail.smtp_host | 127.0.0.1 | SMTP 主机名或 IP,1..=255 可见 ASCII 字符 |
mail.smtp_port | 587 | SMTP 端口,范围 1..=65535 |
mail.username | 空 | 可选 SMTP 认证用户名;配置时须与非空 mail.password 成对出现 |
mail.password | 空 | 可选 SMTP 认证密码(SecretString,日志与 config show 脱敏) |
mail.from_address | 空 | 可选默认发件人邮箱地址;未配置时每封邮件须显式指定 |
mail.from_name | 空 | 可选默认发件人展示名;仅在同时配置 mail.from_address 时生效 |
mail.tls_mode | starttls | TLS 模式:starttls(强制升级)、implicit(SMTPS)或 none(仅限回环) |
mail.allow_insecure_plaintext | false | 是否显式放行向非回环地址使用 tls_mode = "none" |
mail.connect_timeout | 5s | 建立 TCP/TLS 连接及启动 NOOP 探测超时,范围 100ms..=5m |
mail.send_timeout | 30s | 单封邮件发送总超时,范围 connect_timeout..=10m |
mail.max_recipients | 50 | 单封邮件 to + cc + bcc 总收件人数上限,范围 1..=1000 |
mail.max_attachment_bytes | 20971520(20 MiB) | 单封邮件附件总字节上限,范围 0..=100 MiB(0 表示禁止附件) |
mail.pool_max_connections | 10 | SMTP 连接池最大并发连接数,范围 1..=256 |
mail.pool_min_idle_connections | 0 | SMTP 连接池最小空闲连接数,不大于 pool_max_connections |
mail.pool_idle_timeout | 60s | 空闲连接回收前的最长闲置时间,范围 1s..=1h |
mail.verify_on_startup | false | 是否在服务 ready 阶段向 SMTP 服务端发起 NOOP 连通性检查 |
mail.helo_domain | 空 | 可选自定义 EHLO/HELO 域名,1..=255 非空白字符 |
错误分类与 Prometheus 指标#
MailError 完整实现 CallFailure,对外转 AppErr 时仅返回固定安全文案,绝不泄露上游地址或认证凭据;完整排障明细记录于服务端日志与死信表:
MailError 变体 | 重试分类(FailureClass) | HTTP 状态码 | 错误码 | 典型原因 |
|---|---|---|---|---|
InvalidRequest | Settled(不重试) | 400 | mail_invalid_request | 邮箱格式非法、CRLF 注入、超收件人或附件上限 |
AttachmentNotFound | Settled(不重试) | 404 | mail_attachment_not_found | 对象存储中指定的附件对象不存在 |
AttachmentFailed / TemplateFailed | Settled(不重试) | 500 | mail_attachment_failed / mail_template_failed | 附件权限拒绝、未注册所需插件或模板渲染出错 |
Rejected | Settled(不重试) | 502 | mail_rejected | SMTP 服务端返回 5xx 永久拒收或认证失败 |
AttachmentUnavailable / DeadlineExceeded / Unavailable / Transient | NotExecuted(可安全重试) | 503 | mail_attachment_unavailable / mail_deadline_exceeded / mail_unavailable | 对象存储抖动、调用期限已尽、TLS/建连失败或 SMTP 4xx |
Timeout / Interrupted | Indeterminate(建议带 Message-ID 重试) | 504 / 502 | mail_timeout / mail_interrupted | 发送超时或传输中断,对方可能已收信 |
| 指标 | 类型与标签 | 含义 |
|---|---|---|
kxed_mail_send_total | Counter(outcome) | 发信结局累计次数(ok / invalid / attachment_failed / template_failed / timeout / transient / interrupted / rejected / cancelled) |
kxed_mail_send_duration_seconds | Histogram | 单次发信端到端耗时(含模板渲染与附件拉取,单位秒) |
kxed_mail_attachment_bytes | Histogram | 发信成功时的单封邮件附件总字节数分布 |
kxed_mail_in_flight | Gauge | 当前正在发送中的在途邮件数 |