rust-imap/examples/basic.rs
Edward Rudd bb39460491 Change the client builder so that it abstracts away connecting to TLS or non-TLS connections and what TLS provider is used.
- this allows a more transparent and versatile usage of the library as one can simply compile it as-is and then use the builder to configure where we connect and how we connect without having to be concerned about what type is used for the imap::Client / imap::Session
2023-10-05 17:32:58 -04:00

41 lines
1.4 KiB
Rust

extern crate imap;
fn main() {
// To connect to the gmail IMAP server with this you will need to allow unsecure apps access.
// See: https://support.google.com/accounts/answer/6010255?hl=en
// Look at the gmail_oauth2.rs example on how to connect to a gmail server securely.
fetch_inbox_top().unwrap();
}
fn fetch_inbox_top() -> imap::error::Result<Option<String>> {
let client = imap::ClientBuilder::new("imap.example.com", 993).connect()?;
// the client we have here is unauthenticated.
// to do anything useful with the e-mails, we need to log in
let mut imap_session = client
.login("me@example.com", "password")
.map_err(|e| e.0)?;
// we want to fetch the first email in the INBOX mailbox
imap_session.select("INBOX")?;
// fetch message number 1 in this mailbox, along with its RFC822 field.
// RFC 822 dictates the format of the body of e-mails
let messages = imap_session.fetch("1", "RFC822")?;
let message = if let Some(m) = messages.iter().next() {
m
} else {
return Ok(None);
};
// extract the message's body
let body = message.body().expect("message did not have a body!");
let body = std::str::from_utf8(body)
.expect("message was not valid utf-8")
.to_string();
// be nice to the server and log out
imap_session.logout()?;
Ok(Some(body))
}