|
| 1 | +use async_imap::error::{Error, Result}; |
| 2 | +use async_std::prelude::*; |
| 3 | +use std::env; |
| 4 | +use tokio::runtime::Runtime; |
| 5 | + |
| 6 | +fn main() -> Result<()> { |
| 7 | + let mut rt = Runtime::new().expect("unable to create runtime"); |
| 8 | + |
| 9 | + rt.block_on(async { |
| 10 | + let args: Vec<String> = env::args().collect(); |
| 11 | + if args.len() != 4 { |
| 12 | + eprintln!("need three arguments: imap-server login password"); |
| 13 | + Err(Error::Bad("need three arguments".into())) |
| 14 | + } else { |
| 15 | + let res = fetch_inbox_top(&args[1], &args[2], &args[3]).await?; |
| 16 | + println!("**result:\n{}", res.unwrap()); |
| 17 | + Ok(()) |
| 18 | + } |
| 19 | + }) |
| 20 | +} |
| 21 | + |
| 22 | +async fn fetch_inbox_top(imap_server: &str, login: &str, password: &str) -> Result<Option<String>> { |
| 23 | + let tls = async_native_tls::TlsConnector::new(); |
| 24 | + |
| 25 | + // we pass in the imap_server twice to check that the server's TLS |
| 26 | + // certificate is valid for the imap_server we're connecting to. |
| 27 | + let client = async_imap::connect((imap_server, 993), imap_server, tls).await?; |
| 28 | + println!("-- connected to {}:{}", imap_server, 993); |
| 29 | + |
| 30 | + // the client we have here is unauthenticated. |
| 31 | + // to do anything useful with the e-mails, we need to log in |
| 32 | + let mut imap_session = client.login(login, password).await.map_err(|e| e.0)?; |
| 33 | + println!("-- logged in a {}", login); |
| 34 | + |
| 35 | + // we want to fetch the first email in the INBOX mailbox |
| 36 | + imap_session.select("INBOX").await?; |
| 37 | + println!("-- INBOX selected"); |
| 38 | + |
| 39 | + // fetch message number 1 in this mailbox, along with its RFC822 field. |
| 40 | + // RFC 822 dictates the format of the body of e-mails |
| 41 | + let messages_stream = imap_session.fetch("1", "RFC822").await?; |
| 42 | + let messages: Vec<_> = messages_stream.collect::<Result<_>>().await?; |
| 43 | + let message = if let Some(m) = messages.first() { |
| 44 | + m |
| 45 | + } else { |
| 46 | + return Ok(None); |
| 47 | + }; |
| 48 | + |
| 49 | + // extract the message's body |
| 50 | + let body = message.body().expect("message did not have a body!"); |
| 51 | + let body = std::str::from_utf8(body) |
| 52 | + .expect("message was not valid utf-8") |
| 53 | + .to_string(); |
| 54 | + println!("-- 1 message received, logging out"); |
| 55 | + |
| 56 | + // be nice to the server and log out |
| 57 | + imap_session.logout().await?; |
| 58 | + |
| 59 | + Ok(Some(body)) |
| 60 | +} |
0 commit comments