Rust Requires Chilkat v11.0.0+
Rust
Scan for Emails with Attachments and Save Attachments to Files
Scan for emails with attachments and save attachments.Chilkat Rust Downloads
// 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;
}
// 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 email headers into a bundle object:
let bundle = chilkat::EmailBundle::new();
let headers_only = true;
if imap.fetch_msg_set(headers_only, &message_set, &bundle).is_err() {
println!("{}", imap.last_error_text());
return;
}
// Scan for emails with attachments, and save the attachments
// to a sub-directory.
let full_email = chilkat::Email::new();
let email_header = chilkat::Email::new();
let mut i = 0;
while i < bundle.message_count() {
// The bundle contains email headers..
let _ = bundle.email_at(i, &email_header);
// Does this email have attachments?
// Use GetMailNumAttach because the attachments
// are not actually in the email object because
// we only downloaded headers.
let num_attach = imap.get_mail_num_attach(&email_header);
if num_attach > 0 {
// Download the entire email and save the
// attachments. (Remember, we
// need to download the entire email because
// only the headers were previously downloaded.
// The ckx-imap-uid header field is added when
// headers are downloaded. This makes it possible
// to get the UID from the email object.
let uid_str = email_header.get_header_field("ckx-imap-uid").unwrap_or_default();
let uid = uid_str.parse::<i32>().unwrap_or(0);
if imap.fetch_email(false, uid as u32, true, &full_email).is_err() {
println!("{}", imap.last_error_text());
return;
}
let _ = full_email.save_all_attachments("attachmentsDir").is_ok();
for j in 0..num_attach {
let filename = imap.get_mail_attach_filename(&email_header, j).unwrap_or_default();
println!("{}", filename);
}
}
i = i + 1;
}
// Disconnect from the IMAP server.
let _ = imap.disconnect().is_ok();