Skip to content

Instantly share code, notes, and snippets.

@gembin
Last active April 21, 2020 06:58
Show Gist options
  • Save gembin/8b93b01f5af8f64e3253b7b7d5d31e0c to your computer and use it in GitHub Desktop.
Save gembin/8b93b01f5af8f64e3253b7b7d5d31e0c to your computer and use it in GitHub Desktop.
Send email with lettre

Introduction

https://github.com/lettre/lettre is a library to send emails over SMTP from our Rust applications.

Cargo.toml

lettre = "0.9.2"
lettre_email = "0.9.2"
native-tls = "0.2"

Gmail App password

An App Password is a 16-digit passcode that gives a non-Google app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on.

Create & use App Passwords.

Gmail SMTP

use std::convert::Into;

use lettre::{ClientSecurity, ClientTlsParameters, SmtpClient, Transport};
use lettre::smtp::{authentication::{Credentials, Mechanism}, ConnectionReuseParameters};
use lettre_email::Email;
use native_tls::{Protocol, TlsConnector};

let email = Email::builder()
        // Addresses can be specified by the tuple (email, alias)
        .to(("to_xxx@xxx.com", "xxx_alias"))
        .from("from_xxx@gmail.com")
        .subject("Hello world!")
        .alternative("<h2>Hello world!</h2>", "Hello world!")
        .build()
        .unwrap();

    let mut tls_connector = TlsConnector::builder()
        .min_protocol_version(Some(Protocol::Tlsv12))
        .build()
        .unwrap();
    let tls_parameters = ClientTlsParameters::new("smtp.gmail.com".to_string(), tls_connector);

    let mut mailer = SmtpClient::new(
        ("smtp.gmail.com", 465), ClientSecurity::Wrapper(tls_parameters))
        .unwrap()
        .credentials(Credentials::new(
            "from_xxx@gmail.com".to_string(),
            "xxx_app_password".to_string(),
        ))
        // Enable SMTP UTF8 if the server supports it
        .smtp_utf8(true)
        // Configure expected authentication mechanism
        .authentication_mechanism(Mechanism::Plain)
        // Enable connection reuse
        .connection_reuse(ConnectionReuseParameters::ReuseUnlimited)
        .transport();

    // Send the email
    let result = mailer.send(email.into());
    println!("result: {:?}", &result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment