跳转至

Actix Web

适用于 Actix Web(Rust)应用的集成指南。Mailexam 作为 SMTP 服务器接入;发送使用 lettre crate 及基于 Tokio 的异步传输(Actix Web 4 运行于 Tokio)。

前置条件

  • Mailexam 账户,以及已创建并具备 SMTP 凭据的项目
  • Rust 1.70+ 及 Actix Web 4 项目。

从项目的欢迎邮件(或控制台)中复制:

  • YOUR_LOGIN — SMTP 登录名(例如 xxxxx);
  • YOUR_PASSWORD — SMTP 密码(与登录名成对的唯一凭据);
  • 主机 — YOUR_LOGIN.mailexam.cn登录名一致;见下方代码)。

1. 依赖

Cargo.toml 中:

[dependencies]
actix-web = "4"
serde = { version = "1", features = ["derive"] }
lettre = { version = "0.11", default-features = false, features = [
    "builder",
    "smtp-transport",
    "tokio1-rustls-tls",
] }

从环境加载配置(可选):

dotenvy = "0.15"

2. 环境变量

项目根目录的 .env 文件(勿将密码提交到 git):

MAILEXAM_LOGIN=YOUR_LOGIN
MAILEXAM_PASSWORD=YOUR_PASSWORD
MAILEXAM_PORT=587
MAIL_FROM=noreply@example.test

主机由登录名构建:{MAILEXAM_LOGIN}.mailexam.cn

发件人地址

MAIL_FROM 可以是任意测试地址——邮件进入 Mailexam,而非真实收件人。

备选端口

MAILEXAM_PORT=587

使用 AsyncSmtpTransport::starttls_relay(见下文)。

MAILEXAM_PORT=2525
MAILEXAM_PORT=25

不使用 starttls_relay,改用 AsyncSmtpTransport::builder(...).port(25) 且不强制 TLS——仅在网络环境允许时。

3. 邮件发送模块

Axum 相同:MailConfig::from_env() 及通过 lettresend_test

// src/mail.rs
use lettre::message::header::ContentType;
use lettre::transport::smtp::authentication::Credentials;
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};

#[derive(Clone)]
pub struct MailConfig {
    pub host: String,
    pub port: u16,
    pub username: String,
    pub password: String,
    pub from: String,
}

impl MailConfig {
    pub fn from_env() -> Self {
        let login = std::env::var("MAILEXAM_LOGIN").expect("MAILEXAM_LOGIN");
        Self {
            host: format!("{login}.mailexam.cn"),
            port: std::env::var("MAILEXAM_PORT")
                .unwrap_or_else(|_| "587".into())
                .parse()
                .expect("MAILEXAM_PORT"),
            username: login,
            password: std::env::var("MAILEXAM_PASSWORD").expect("MAILEXAM_PASSWORD"),
            from: std::env::var("MAIL_FROM")
                .unwrap_or_else(|_| "noreply@example.test".into()),
        }
    }
}

pub async fn send_test(
    config: &MailConfig,
    to: &str,
    subject: &str,
    body: &str,
) -> Result<(), lettre::transport::smtp::Error> {
    let email = Message::builder()
        .from(config.from.parse().expect("MAIL_FROM"))
        .to(to.parse().expect("recipient"))
        .subject(subject)
        .header(ContentType::TEXT_PLAIN)
        .body(body.to_string())
        .expect("message");

    let creds = Credentials::new(config.username.clone(), config.password.clone());

    let mailer = AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&config.host)?
        .port(config.port)
        .credentials(creds)
        .build();

    mailer.send(email).await
}

4. Actix Web 处理器

// src/main.rs
mod mail;

use actix_web::{post, web, App, HttpResponse, HttpServer, Responder};
use mail::MailConfig;
use serde::Deserialize;

#[derive(Deserialize)]
struct SendRequest {
    to: String,
    subject: Option<String>,
    body: Option<String>,
}

#[post("/mail/test")]
async fn send_mail(
    config: web::Data<MailConfig>,
    payload: web::Json<SendRequest>,
) -> impl Responder {
    mail::send_test(
        &config,
        &payload.to,
        payload.subject.as_deref().unwrap_or("Actix + Mailexam"),
        payload.body.as_deref().unwrap_or("来自 Actix 的 Mailexam 测试"),
    )
    .await
    .expect("smtp send");

    HttpResponse::Ok().body("ok")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    dotenvy::dotenv().ok();

    let config = web::Data::new(MailConfig::from_env());

    HttpServer::new(move || {
        App::new()
            .app_data(config.clone())
            .service(send_mail)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

启动并验证:

cargo run
curl -X POST http://127.0.0.1:8080/mail/test \
  -H 'Content-Type: application/json' \
  -d '{"to":"user@example.test","subject":"测试","body":"你好"}'

邮件将出现在 Mailexam 控制台 → 您的项目 → 收件箱。

5. 本地开发与 CI

环境 建议
local 带个人 Mailexam 项目的 .env
CI GitLab CI/CD Variables 中的密钥 MAILEXAM_LOGINMAILEXAM_PASSWORD

.gitlab-ci.yml 示例:

variables:
  MAILEXAM_LOGIN: $MAILEXAM_LOGIN
  MAILEXAM_PASSWORD: $MAILEXAM_PASSWORD
  MAILEXAM_PORT: "587"
  MAIL_FROM: "noreply@example.test"

集成测试发送邮件后,通过 Mailexam API 验证投递。

6. 常见问题

TLS 或连接错误

  • 主机须为 {login}.mailexam.cn,其中 {login} 与邮件中的 MAILEXAM_LOGIN 相同。
  • 登录名和密码为邮件成对凭据;勿混用不同项目的凭据。
  • 587 端口使用 starttls_relay,而非 465 上的 SMTPS。

控制台中看不到邮件

  • 确认查看的是同一 Mailexam 项目的收件箱。
  • 查看 Actix worker 日志:send_test 失败时会出现 SMTP 错误。

编译 lettre

  • TLS 需要 tokio1-rustls-tls 特性(或按需使用 tokio1-native-tls)。

端口被占用

  • 默认监听 8080;如有冲突,请在 .bind(...) 中更改地址。

参见