十二、Rust + Lettre 发送邮件
本次案例,是在前面工程基础上,进行的扩展。
1、添加依赖
Cargo.toml
[package]
...
[dependencies]
...
lettre = "0.10.0-alpha.4" # e-mail
2、编写代码
新建 module/email/mod.rs
pub mod email {
pub fn send() {
use lettre::{Message, SmtpTransport, Transport};
use lettre::transport::smtp::authentication::Credentials;
let email = Message::builder()
.from("From <from@126.com>".parse().unwrap()) // 发件人
.to("To <to@126.com>".parse().unwrap()) // 收件人
.subject("Happy new year") // 主题
.body("Be happy!") // 邮件内容
.unwrap();
// 邮件服务器账号:
// username 需包含 @xxx.com 等后缀
// password 邮箱 -> 设置,开启 smtp -> 得到 授权密码
let creds = Credentials::new("from@126.com".to_string(), "Smtp授权密码".to_string());
// Open a remote connection to gmail
let mailer = SmtpTransport::relay("smtp.126.com").unwrap().credentials(creds).build();
// Send the email
match mailer.send(&email) {
Ok(_) => log::debug!("Email sent successfully!"),
Err(e) => log::error!("Could not send email: {:?}", e),
}
}
}
3、测试
mail.rs
...
use crate::module::email::email;
...
#[actix_web::main]
async fn main() -> std::io::Result<()> {
boot::start();
email::send();
HttpServer::new(move || App...
...
}
Mac + Clion 环境下:Control + D 。
查看日志:
2020-11-18 17:29:48 INFO [favorites::boot::db] - DataSource postgres://username:password@ip:5432/postgres 5 ~ 15
2020-11-18 17:29:48 DEBUG [favorites::module::email::email] - Email sent successfully!
2020-11-18 17:29:48 INFO [actix_server::builder] - Starting 8 workers
2020-11-18 17:29:48 INFO [actix_server::builder] - Starting "actix-web-service-0.0.0.0:8080" service on 0.0.0.0:8080
完活 ~