Send emails from the Rust program by using the SMTP library lettre. The lettre rust crate is a powerful SMTP Rust library to send email. This library supports the async method.

Navigate to specific topics instantly by clicking on the entries in the table of contents below.

  1. Sending a simple plain.txt email from Rust
  2. Send emails to multiple recipients
  3. HTML email from Rust
  4. Send email with attachments

Sending A Simple Plain-Text email from Rust

First, find SMTP sandbox credentials, Gmail SMTP credentials, or Purchase Commercial Email.

MailMug.net provides a free SMTP sandbox account. Sign up now then create an Inbox from the dashboard.

Signup > Create Inbox > Settings > Click on Show credentials.

SMPT Sandbox account

OR

Sending Email with Rust via Gmail

Google (Gmail) provides a free SMTP server. It needs to enable two-step verification for your Gmail account.

Next, generate an app password by following these steps:

  1. Visit your Google account settings.
  2. Navigate to the Security section.
  3. Select 2-Step Verification > App passwords (bottom).
  4. Create a new app password.
smtp gmail password

Now, input the credentials as outlined below.

Host: smtp.gmail.com
 
Username: youremail@gmail.com
 
Password: {app password}
 
Secure(SSL)
 
Port(465)

Example Send Email With Rust

Create the hello_mail project. Then install the SMTP library. Go to the project directory and enter the following command on the terminal.

cargo new  hello_mail --bin 
cd hello_mail
cargo add lettre

Next, Add the following code to src/main.rs file.

use lettre::{message::header::ContentType, Message, SmtpTransport, Transport};

fn main() {

    let email = Message::builder()
        .from("nobody@domain.tld".parse().unwrap())
        .reply_to("yuin@domain.tld".parse().unwrap())
        .to("hei@domain.tld".parse().unwrap())
        .subject("Happy new year")
        .header(ContentType::TEXT_PLAIN)
        .body(String::from("Be happy!"))
        .unwrap();

    let username = "username here";
    let password = "pass here";
    let server = "smtp.server.net";
    let port = "2525";
    let url = format!("smtp://{username}:{password}@{server}:{port}");

    let mailer =
    SmtpTransport::from_url( &url )
        .unwrap().build();
    
    // Send the email
    match mailer.send(&email) {
        Ok(_) => println!("Email sent successfully!"),
        Err(e) => panic!("Could not send email: {e:?}"),
    }
}

Run the rust code. It will start to send. Now, you can see the email in the inbox.

Send Emails To Multiple Recipients With Rust

Chaining .to(), .cc(), and .bcc() methods to send emails to multiple recipients. Each emails will added by parsing the string.

use lettre::{message::header::ContentType, Message, SmtpTransport, Transport};

fn main() {

    let email = Message::builder()
        .from("nobody@domain.tld".parse().unwrap())
        .reply_to("yuin@domain.tld".parse().unwrap())
        .to("hei@domain.tld".parse().unwrap())
        .to("to1@gmail.com".parse().unwrap())
        .bcc("bcc@gmail.com".parse().unwrap())
        .bcc("bcc2@gmail.com".parse().unwrap())
        .cc("cc1@gmail.com".parse().unwrap())
        .cc("cc@gmail.com".parse().unwrap())
        .subject("Happy new year")
        .header(ContentType::TEXT_PLAIN)
        .body(String::from("Be happy!"))
        .unwrap();


    let username = "username here";
    let password = "pass";
    let server = "smtp.mailmug.net";
    let port = "2525";
    let url = format!("smtp://{username}:{password}@{server}:{port}");

    let mailer =
    SmtpTransport::from_url( &url )
        .unwrap().build();
    
    // Send the email
    match mailer.send(&email) {
        Ok(_) => println!("Email sent successfully!"),
        Err(e) => panic!("Could not send email: {e:?}"),
    }
}

Example Output

email to multiple recipients using Rust

HTML Email From Rust

We need to set the body content type to text/html. The MultiPart type represents a MIME multipart message, which is a message composed of multiple parts, each potentially of a different media type. The SinglePart type represents a MIME single-part message.

use lettre::{Message, SmtpTransport, Transport};
use lettre::message::{header, MultiPart, SinglePart};

fn main() {

    let email = Message::builder()
        .from("nobody@domain.tld".parse().unwrap())
        .reply_to("Yuin <yuin@domain.tld>".parse().unwrap())
        .to("Hei <hei@domain.tld>".parse().unwrap())
        .subject("Happy new year")
        .multipart(
            MultiPart::related()
                .singlepart(
                    SinglePart::builder()
                        .header(header::ContentType::TEXT_HTML)
                        .body(String::from(
                            "<html>
                                <body>
                                    <h1>Hello!</h1>
                                    <p>This is a <strong>test mail</strong> from Rust Lang</p>
                                </body>
                            </html>",
                        )),
                )
            ).unwrap();

    let username = "USER NAME";
    let password = "PASS";
    let server = "smtp.mailmug.net";
    let port = "2525";
    let url = format!("smtp://{username}:{password}@{server}:{port}");

    let mailer =
    SmtpTransport::from_url( &url )
        .unwrap().build();
    
    // Send the email
    match mailer.send(&email) {
        Ok(_) => println!("Email sent successfully!"),
        Err(e) => panic!("Could not send email: {e:?}"),
    }
}

Send Emails With Attachments

Send emails attached file from Rust with Attachment struct. First, read file binary data and store it in a variable. Then create an image body with binary data. Eg: Body::new(image)

Then attached by singlepart method. You can send multiple files by chains of singlepart.

use lettre::{Message, SmtpTransport, Transport};
use lettre::message::{header, MultiPart, SinglePart, Body, Attachment};
use std::fs;

fn main() {
    let image_name = "test.png";
    let image: Vec<u8>= fs::read("test.png").unwrap(); 
    let image_body = Body::new(image);

    let email = Message::builder()
        .from("nobody@domain.tld".parse().unwrap())
        .reply_to("Yuin <yuin@domain.tld>".parse().unwrap())
        .to("Hei <hei@domain.tld>".parse().unwrap())
        .subject("Happy new year")
        .multipart(
            MultiPart::related()
                .singlepart(
                    SinglePart::builder()
                        .header(header::ContentType::TEXT_HTML)
                        .body(String::from(
                            "<html>
                                <body>
                                    <h1>Hello!</h1>
                                    <p>This is a <strong>test mail</strong> from Rust Lang</p>
                                </body>
                            </html>",
                        )),
                )
                .singlepart(
                    Attachment::new(image_name.to_string())
                    .body(image_body, "image/png".parse().unwrap()),
                )
                
            ).unwrap();

    let username = "username ";
    let password = "pass";
    let server = "smtp.mailmug.net";
    let port = "2525";
    let url = format!("smtp://{username}:{password}@{server}:{port}");

    let mailer =
    SmtpTransport::from_url( &url )
        .unwrap().build();
    
    // Send the email
    match mailer.send(&email) {
        Ok(_) => println!("Email sent successfully!"),
        Err(e) => panic!("Could not send email: {e:?}"),
    }
}


By admin

Leave a Reply

Your email address will not be published. Required fields are marked *