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

IMAP Download and Verify Signed MIME

See more IMAP Examples

Downloads the original MIME of a digitally signed email and saves the .p7s signature along with other MIME parts. It then imports the email into a Chilkat email object to unwrap the S/MIME and verify the signature, and subsequently saves the attachments if they haven't been saved already.

Chilkat Rust Downloads

Rust

// This example requires 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;
}

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;
}

// Download the 1st email (as MIME) in the Inbox by sequence number.
let sb_mime = chilkat::StringBuilder::new();
if imap.fetch_single_as_mime_sb(1, false, &sb_mime).is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// Load it into a MIME object and check to see if it is signed
let mime = chilkat::Mime::new();
let _ = mime.load_mime_sb(&sb_mime);
let mut already_saved_parts = false;
if mime.contains_signed_parts() {

    // This will save the .p7s and other parts...
    let st = chilkat::StringTable::new();
    if mime.parts_to_files("c:/temp/qa_output", &st).is_ok() {
        let num_files = st.count();
        let mut i = 0;
        while i < num_files {
            println!("Created: {}", st.string_at(i).unwrap_or_default());
            i = i + 1;
        }

        already_saved_parts = true;
    }

}

// Load the MIME into an Email object.  This unwraps the security layers and verifies signatures.
let email = chilkat::Email::new();
let _ = email.set_from_mime_sb(&sb_mime);

if email.received_signed() {
    println!("This email was signed.");

    // Check to see if the signatures were verified.
    if email.signatures_valid() {
        println!("Digital signature(s) verified.");
        println!("Signer: {}", email.signed_by());

        // The certificate used for signing may be obtained
        // by calling email.LastSignerCert.  Index 0 is the first signer.
        let cert = chilkat::Cert::new();
        if email.last_signer_cert(0, &cert).is_err() {
            println!("Failed to get signing certificate object.");
        } else {
            println!("Signing cert: {}", cert.subject_cn());
        }

    } else {
        println!("Digital signature verification failed.");
    }

} else {
    println!("This email was not signed.");
}

if !already_saved_parts {
    let _ = email.save_all_attachments("c:/temp/qa_output");
}