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

Delete Email Individually (One at a time) from an IMAP Mailbox

Downloads email from an IMAP mailbox and deletes emails individually (one by one).

Chilkat Rust Downloads

Rust

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

let imap = chilkat::Imap::new();

// Connect to an IMAP server.
// Use TLS
imap.set_ssl(true);
imap.set_port(993);
if imap.connect("imap.example.com").is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// Login
if imap.login("myLogin", "myPassword").is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// Select an IMAP mailbox
if imap.select_mailbox("Inbox").is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// We can choose to fetch UIDs or sequence numbers.
let fetch_uids = true;

// Get the message IDs of all the emails in the mailbox
let message_set = chilkat::MessageSet::new();
if imap.query_mbx("ALL", fetch_uids, &message_set).is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// Fetch the emails into a bundle object:
let bundle = chilkat::EmailBundle::new();
let headers_only = false;
if imap.fetch_msg_set(headers_only, &message_set, &bundle).is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// To mark a complete set of emails for deletion, call SetFlags:
if imap.set_flags(&message_set, "Deleted", 1).is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// Messages can also be marked for deletion individually:
// Loop over the bundle and mark each message for deletion.
let email = chilkat::Email::new();
let mut i = 0;
let num_emails = bundle.message_count();
while i < num_emails {
    let _ = bundle.email_at(i, &email);

    println!("{}", email.from());
    println!("{}", email.subject());

    // To delete this email, set the "Deleted" flag to 1.
    // The email is not actually deleted until Expunge or
    // ExpungeAndClose is called.
    if imap.set_mail_flag(&email, "Deleted", 1).is_err() {
        println!("{}", imap.last_error_text());
        return;
    }

    println!("--");

    i = i + 1;
}

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

// Disconnect from the IMAP server.
let _ = imap.disconnect().is_ok();