How to send an email with rust
There are a few different ways you can send email from Rust. Here are three options:
- Use an email library: There are several libraries available for sending email from Rust, including
lettre
,rust-email
, andmailparse
. These libraries provide APIs for constructing and sending email messages. - Use the
sendmail
command: You can use Rust'sstd::process::Command
to invoke thesendmail
command, which is a common Unix utility for sending email. This approach is simple, but it requires thatsendmail
be installed on the system. - Use a web API: Many email services (e.g., Gmail, Outlook, etc.) provide APIs that you can use to send email. This approach requires an internet connection and an API key, but it allows you to send email from Rust without needing to install any libraries or utilities.
Here's an example of how you could use the lettre
library to send an email from Rust:
send an email with rust
use lettre::{SmtpClient, Transport, EmailTransport, EmailAddress}; use lettre_email::Email; fn main() { // Create the email let email = Email::builder() .to(EmailAddress::new("recipient@example.com")) .from(EmailAddress::new("sender@example.com")) .subject("Hello from Rust") .body("This is a message sent from Rust using the lettre library.") .build() .unwrap(); // Create the SMTP client let client = SmtpClient::new_simple("localhost:25").unwrap(); // Send the email let result = client.send(email.into()); if result.is_ok() { println!("Email sent successfully!"); } else { println!("Error sending email: {:?}", result); } }
Here's one more example of how you can send an email using Rust:
use lettre::{Message, Transport}; use lettre_email::Email; fn main() { // Create the email let email = Email::builder() .to("recipient@example.com") .from("sender@example.com") .subject("Hello") .body("Hello, world!") .build() .unwrap(); // Create the transport let mut transport = Transport::new(); // Send the email match transport.send(&email) { Ok(_) => println!("Email sent successfully!"), Err(e) => println!("Error sending email: {}", e), } }
This example uses the lettre
crate to send the email. You will need to add lettre
and lettre_email
to your Cargo.toml
file:
[dependencies] lettre = "0.10" lettre_email = "0.10"
This example sends the email using the send
method of the Transport
struct, which sends the email using SMTP. You can also use other methods provided by Transport
to send the email using different methods, such as sendmail or a custom transport.
I hope this helps! Let me know if you have any questions.