spring-mail插件

spring-mail是针对lettre的自动装配

lettre Repo stars downloads lettre是Rust最流行的邮件客户端,并且支持异步API。spring-mail主要使用它的tokio异步API。

crates.io Documentation

依赖

spring-mail = { version = "0.1.1" }

配置项

[mail]
host = "smtp.gmail.com"                                 # SMTP邮件服务器地址,
port = 465                                              # SMTP服务器端口号
secure = true                                           # 响应超时时间,单位毫秒
auth = { user = "user@gmail.com", password = "passwd" } # 认证信息

组件

配置完上述配置项后,插件会自动注册一个MailerSTMP异步客户端。该对象是lettre::AsyncSmtpTransport<Tokio1Executor>的别名。

pub type Mailer = lettre::AsyncSmtpTransport<Tokio1Executor>;

提取插件注册的Component

MailPlugin插件为我们自动注册了一个SMTP客户端,我们可以使用Component从AppState中提取这个连接池,Component是一个axum的extractor

async fn send_mail(Component(mailer): Component<Mailer>) -> Result<impl IntoResponse> {
    let email = Message::builder()
        .from("NoBody <nobody@domain.tld>".parse().unwrap())
        .reply_to("Yuin <yuin@domain.tld>".parse().unwrap())
        .to("hff1996723@163.com".parse().unwrap())
        .subject("Happy new year")
        .header(ContentType::TEXT_PLAIN)
        .body(String::from("Be happy!"))
        .unwrap();
    let resp = mailer.send(email).await.context("send mail failed")?;
    Ok(Json(resp))
}

完整代码参考mail-example