Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

Find an email by subject and fetch it by IMAP UID

See more Email Object Examples

Search the selected INBOX by subject and fetch the first matching UID into an Email. The example requests complete attachment bodies and uses peek mode to preserve the read flag. Configure your own IMAP TLS endpoint and credentials.

Chilkat Rust Downloads

Rust

// Assumes Chilkat is unlocked. See Global Unlock Sample.

let imap = chilkat::Imap::new();
imap.set_ssl(true);
imap.set_port(993);
imap.set_require_ssl_cert_verify(true);
imap.set_peek_mode(true);
imap.set_auto_download_attachments(true);
if imap.connect("imap.example.com").is_err() {
    println!("{}", imap.last_error_text());
    return;
}

if imap.login("MAIL_USER", "MAIL_PASSWORD").is_err() {
    println!("{}", imap.last_error_text());
    return;
}

if imap.select_mailbox("INBOX").is_err() {
    println!("{}", imap.last_error_text());
    return;
}

let matches = chilkat::MessageSet::new();
if imap.query_mbx("SUBJECT \"Sample message\"", true, &matches).is_err() {
    println!("{}", imap.last_error_text());
    return;
}

if matches.count() == 0 {
    println!("No matching message in INBOX.");
    if imap.disconnect().is_err() {
        println!("{}", imap.last_error_text());
        return;
    }

    return;
}

// The search returned UIDs. Use the same identifier type for the fetch.
let uid = matches.get_id(0);
let email = chilkat::Email::new();
if imap.fetch_email(false, uid, true, &email).is_err() {
    println!("{}", imap.last_error_text());
    return;
}

println!("Mailbox INBOX, UIDVALIDITY {}, UID {}", imap.uid_validity(), uid);
if imap.disconnect().is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// The downloaded Email remains usable after disconnecting.
println!("Subject: {}  Files: {}", email.subject(), email.num_attachments());

if email.save_eml("imap-received.eml").is_err() {
    println!("{}", email.last_error_text());
    return;
}

println!("Saved imap-received.eml.");