Last active
March 29, 2024 22:25
-
-
Save harryhanYuhao/029a8b6e28c3c1be95074432155092cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cargo add lettre | |
use lettre::address::Address; | |
use lettre::message::header::ContentType; | |
use lettre::message::Mailbox; | |
use lettre::transport::smtp::authentication::Credentials; | |
use lettre::{Message, SmtpTransport, Transport}; | |
struct EmailInfo { | |
credential_username: String, | |
credential_password: String, | |
sender_addr: String, | |
sender_name: String, | |
reply_addr: String, | |
destination_addr: String, | |
subject: String, | |
content: String, | |
is_html: bool, | |
} | |
fn send_email(email_info: &EmailInfo) -> Result<(), Box<dyn std::error::Error>> { | |
// Define the email | |
let source_address = email_info.sender_addr.parse::<Address>()?; | |
let name: Option<String> = Some(email_info.sender_name.to_owned()); | |
let send_mailbox = Mailbox::new(name, source_address); | |
let reply_addr = email_info.reply_addr.parse::<Address>()?; | |
let destination_addr = email_info.destination_addr.parse::<Address>()?; | |
let content_type = match email_info.is_html { | |
true => ContentType::TEXT_HTML, | |
false => ContentType::TEXT_PLAIN, | |
}; | |
let email = Message::builder() | |
.from(send_mailbox) | |
.reply_to(reply_addr.into()) | |
.to(destination_addr.into()) | |
.subject(email_info.subject.to_owned()) | |
.header(content_type) | |
.body(String::from(email_info.content.to_owned())) | |
.unwrap(); | |
// Create SMTP client credentials using username and password | |
let creds = Credentials::new( | |
email_info.credential_username.to_owned(), | |
email_info.credential_password.to_owned(), | |
); | |
// Open a secure connection to the SMTP server using STARTTLS | |
let mailer = SmtpTransport::starttls_relay("smtp.fastmail.com") | |
.unwrap() // Unwrap the Result, panics in case of error | |
.credentials(creds) // Provide the credentials to the transport | |
.build(); // Construct the transport | |
// Attempt to send the email via the SMTP transport | |
mailer.send(&email)?; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment