十二、Rust + Lettre 发送邮件

十二、Rust + Lettre 发送邮件

  本次案例,是在前面工程基础上,进行的扩展。

1、添加依赖

  Cargo.toml

1
2
3
4
5
[package]
...
[dependencies]
...
lettre = "0.10.0-alpha.4"   # e-mail

2、编写代码

  新建 module/email/mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
pub mod email {<!-- -->
    pub fn send() {<!-- -->
        use lettre::{<!-- -->Message, SmtpTransport, Transport};
        use lettre::transport::smtp::authentication::Credentials;

        let email = Message::builder()
            .from("From <[email protected]>".parse().unwrap())  // 发件人
            .to("To <[email protected]>".parse().unwrap())        // 收件人
            .subject("Happy new year")  // 主题
            .body("Be happy!")          // 邮件内容
            .unwrap();

        // 邮件服务器账号:
        // username 需包含 @xxx.com 等后缀
        // password 邮箱 -> 设置,开启 smtp -> 得到 授权密码
        let creds = Credentials::new("[email protected]".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

1
2
3
4
5
6
7
8
9
10
...
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 。

查看日志:

1
2
3
4
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

  完活 ~