Rust lettre使用腾讯企业邮箱发送邮件参数配置

邮件发送这个在Rust中总是有点问题,之前用lettre低版本测试没问题,后来腾讯企业邮箱升级做了一些限制调整,我调了好长时间,终于调通了。

Cargo.toml

【国内直连ChatGPT 29元起】
国内直连ChatGPT,Plus会员每月29元起,支持最新o1模型探索更多领域,无需注册OpenAI账号。

[dependencies]
lettre = "0.10"

目前lettre最新版本就是0.10版本了。

sample.rs

use lettre::message::header::ContentType;
use lettre::transport::smtp::authentication::{Credentials, Mechanism};
use lettre::transport::smtp::client::{TlsParameters, Tls};
use lettre::{Message, SmtpTransport, Transport};
use log::{info, warn};
use crate::router;

fn send_mail(to_addr: &str, subject: &str, body: String) -> anyhow::Result<()> {
  let email: Message = Message::builder()
    .from("Qttc <blog@qttc.net>".parse()?)
    .reply_to("Qttc <blog@qttc.net>".parse()?)
    .to(to_addr.parse()?)
    .subject(subject)
    .header(ContentType::TEXT_HTML)
    .body(body)?;

  let creds: Credentials = Credentials::new(
    "[Account]".to_string(),
    "[Password]".to_string(),
  );

  let smtp_host: &str = "smtp.exmail.qq.com";
  let tls_params: TlsParameters = TlsParameters::new("exmail.qq.com".to_string())?;
  let tls: Tls = Tls::Wrapper(tls_params);

  let mailer: SmtpTransport = SmtpTransport::relay(smtp_host)?
    .port(465)
    .credentials(creds)
    .authentication(vec![Mechanism::Login])
    .tls(tls)
    .build();

  match mailer.send(&email) {
    Ok(_) => info!("Email sent {} successfully!", &to_addr),
    Err(e) => warn!("Error sending email {} was error: {}", &to_addr, e),
  };

  Ok(())
}

注意,Tls配置的域名是exmail.qq.com,不是smtp.exmail.qq.com。另外,tls()方法要求构建的Tls参数不支持异步的AsyncSmtpTransport

pub fn tls(self, tls: Tls) -> Self Available on crate features native-tls or rustls-tls or boring-tls only.

所以这里只能使用同步的SmtpTransport,那些想尝试异步的就不要徒劳了。

分享

TITLE: Rust lettre使用腾讯企业邮箱发送邮件参数配置

LINK: https://www.qttc.net/552-exmail-qq-lettre-valid.html

NOTE: 原创内容,转载请注明出自琼台博客