Sample code for 30+ languages & platforms
Rust

Send HTML Email with Attachments

See more SMTP Examples

Demonstrates how to send an HTML email with file attachments.

Chilkat Rust Downloads

Rust

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let mailman = chilkat::MailMan::new();

mailman.set_smtp_host("smtp.my-starttls-mail-server.com");

mailman.set_smtp_username("MY-SMTP-USERNAME");
mailman.set_smtp_password("MY-SMTP-PASSWORD");

mailman.set_start_tls(true);
mailman.set_smtp_port(587);

// Create a new email object
let email = chilkat::Email::new();
email.set_subject("Test SMTP API to Send HTML Email with Attachments");
email.set_from("Joe Programmer <joe@my-starttls-mail-server.com>");
let _ = email.add_to("Chilkat Support", "support@chilkatsoft.com");

// Add a plain-text alternative body, which will likely never be seen.
// (It is shown if the receiving email client is incapable of displaying HTML email.)
let _ = email.add_plain_text_alternative_body("This is a plain-text alternative body...");

// Our HTML will include an image, so add the related image here.
let Ok(content_id_starfish) = email.add_related_file("qa_data/jpg/starfish.jpg") else {
    println!("{}", email.last_error_text());
    return;
};

// The src attribute for the image tag is set to the contentIdStarfish:
let sb_html = chilkat::StringBuilder::new();
let _ = sb_html.append("<html><body><p>This is an HTML email with an embedded image.</p>");
let _ = sb_html.append("<p><img src=\"cid:CONTENT_ID_STARFISH\" /></p></body></html>");
let num_replacements = sb_html.replace("CONTENT_ID_STARFISH", &content_id_starfish);

let _ = email.add_html_alternative_body(&sb_html.get_as_string().unwrap_or_default());

// Finally, add some attachments to the email.
// Add a file attachment.
if email.add_file_attachment2("qa_data/pdf/fishing.pdf", "application/pdf").is_err() {
    println!("{}", email.last_error_text());
    return;
}

// Add an attachment where the content is contained in a string.
let content = "This is the content of the 2nd attached file.".to_string();
let _ = email.add_string_attachment("someText.txt", &content);

// Send the HTML email.
if mailman.send_email(&email).is_err() {
    println!("{}", mailman.last_error_text());
    return;
}

if mailman.close_smtp_connection().is_err() {
    println!("Connection to SMTP server not closed cleanly.");
}

println!("HTML email with attachments sent!");