Mail sender using the lettre crate

lettre

lettre

examples/mail-sender/Cargo.toml

[package]
name = "mail-sender"
version = "0.1.0"
edition = "2024"

[dependencies]
anyhow = "1.0.100"
clap = { version = "4.5.53", features = ["derive"] }
lettre = { version = "0.11.19", features = ["file-transport", "sendmail-transport"] }

examples/mail-sender/src/main.rs

use clap::Parser;
use lettre::{FileTransport, Message, SendmailTransport, Transport, message::header::ContentType};
use std::io::Read;

#[derive(Parser)]
struct Cli {
    #[arg(long)]
    from: String,

    #[arg(long)]
    to: String,

    #[arg(long)]
    subject: String,

    #[arg(long)]
    dir: Option<String>,
}

fn main() {
    let args = Cli::parse();
    let mut body = String::new();
    std::io::stdin().read_to_string(&mut body).unwrap();

    let email = Message::builder()
        .from(args.from.parse().unwrap())
        .to(args.to.parse().unwrap())
        .subject(args.subject)
        .header(ContentType::TEXT_PLAIN)
        .body(body)
        .unwrap();

    match args.dir {
        Some(dirname) => {
            let sender = FileTransport::new(dirname);
            let filename = sender.send(&email).unwrap();
            println!("{filename}.eml");
        }
        None => {
            let sender = SendmailTransport::new();
            sender.send(&email).unwrap();
        }
    }
}

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo