Sling Academy
Home/Rust/Sending and Receiving Emails in Rust Using lettre

Sending and Receiving Emails in Rust Using lettre

Last updated: January 06, 2025

Email communication is a crucial part of many applications, and Rust, being a language that emphasizes safety and performance, offers solutions for handling emails effectively through various crates. One such powerful crate is lettre. In this article, we'll explore how to send and receive emails in Rust using lettre.

Introduction to lettre

lettre is a mailer library in Rust designed to send and receive emails effortlessly. It supports the SMTP protocol, which is widely used for email transmission. This crate abstracts the complexities of dealing directly with SMTP servers, allowing developers to send emails with minimal boilerplate code.

Setting Up the Project

First, let's create a new Rust project:

cargo new email_app --bin

Navigate into the project directory:

cd email_app

Open Cargo.toml and add lettre to the dependencies:

[dependencies]
lettre = "0.10.0-alpha.6"
lettre_transport_smtp = "0.8.2-alpha.4"
lettre_email = "0.9.2-alpha.7"

Sending an Email

Let's write a function to send an email using lettre. Create or edit the main.rs file:

use lettre::{Message, SmtpTransport, Transport};
use lettre::transport::smtp::authentication::{Credentials, Mechanism};

fn send_email(recipient: &str, subject: &str, body: &str) {
    let email = Message::builder()
        .from("[email protected]".parse().unwrap())
        .to(recipient.parse().unwrap())
        .subject(subject)
        .body(body.to_string())
        .unwrap();

    let creds = Credentials::new("smtp_username".to_string(), "smtp_password".to_string());

    let mailer = SmtpTransport::builder_dangerous("smtp.domain.com")
        .credentials(creds)
        .authentication(vec![Mechanism::Login])
        .build();

    match mailer.send(&email) {
        Ok(_) => println!("Email sent successfully"),
        Err(e) => eprintln!("Failed to send email: {e}"),
    }
}

Modify and replace the placeholder values such as [email protected], smtp.domain.com, smtp_username, and smtp_password with actual values.

Receiving Emails

Currently, lettre does not provide direct support for receiving emails; it primarily focuses on sending email functionality. For receiving emails, one might need to rely on other libraries or tools such as imap or pop3 crates, based on the required protocol. However, in combination with email services and webhooks, handling incoming email notifications is achievable.

Handling Errors

SMTP operations can fail for many reasons — invalid server credentials, network issues, or server downtime. Therefore, it is crucial to handle these errors gracefully. Modify the send function to capture and react to different errors, for example.

fn main() {
    send_email("[email protected]", "Test Email", "This is a test email.");
}

Here, check the error variants from lettre's error handling system for a robust solution according to your need.

Conclusion

In this article, we explored how to send emails in Rust using the lettre crate. Though lettre is currently limited to sending emails, it is a powerful and flexible option for Rust developers working with email processing applications. Stay connected with the Rust community as more libraries and tools evolve to support a broader range of email-related functionalities.

Next Article: Implementing TLS/SSL in Rust with native-tls or rustls

Previous Article: Understanding Domain Name Resolution in Rust

Series: Networking in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior