use dotenvy::var; use lettre::{ message::{header::ContentType, Mailbox}, transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport, }; fn create_mailer() -> SmtpTransport { // Get the server settings from the env file let smtp_server_name = var("SMTP_SERVER_NAME").expect("SMTP_SERVER_NAME not set"); let smtp_server_port = var("SMTP_SERVER_PORT").expect("SMTP_SERVER_PORT not set"); // Get the username and password from the env file let username = var("EMAIL_USERNAME").expect("EMAIL_USERNAME not set"); let password = var("EMAIL_PASSWORD").expect("EMAIL_PASSWORD not set"); // Create the credentials let creds = Credentials::new(username, password); // Create a connection to our email provider // In this case, we are using Namecheap's Private Email // You can use any email provider you want SmtpTransport::relay(&smtp_server_name) .unwrap() .credentials(creds) .build() } pub fn send_email(subject: String, recipient: String, body: String) { let username = var("EMAIL_USERNAME").expect("EMAIL_USERNAME not set"); // Build the email let email = Message::builder() .from(username.parse::().unwrap()) .to(recipient.parse::().unwrap()) .subject(subject) .header(ContentType::TEXT_HTML) .body(body.to_string()) .unwrap(); let mailer = create_mailer(); // Send the email match mailer.send(&email) { Ok(_) => println!("Basic email sent!"), Err(error) => { println!("Basic email failed to send. {:?}", error); } } } pub fn send_emails(subject: String, recipients: Vec, body: String) { let username = var("EMAIL_USERNAME").expect("EMAIL_USERNAME not set"); // Build the email let mut email = Message::builder() .from(username.parse::().unwrap()) .subject(subject) .header(ContentType::TEXT_HTML) .body(body); for recipient in recipients { email = email.to(recipient.parse::().unwrap()); } }