|
| 1 | +extern crate imap; |
| 2 | +extern crate rustls_connector; |
| 3 | + |
| 4 | +use std::{ |
| 5 | + env, |
| 6 | + error::Error, |
| 7 | + net::TcpStream, |
| 8 | +}; |
| 9 | + |
| 10 | +use dotenv::dotenv; |
| 11 | +use rustls_connector::RustlsConnector; |
| 12 | + |
| 13 | + |
| 14 | +fn main() -> Result<(), Box<dyn Error>> { |
| 15 | + // Read config from environment or .env file |
| 16 | + dotenv().ok(); |
| 17 | + let host = env::var("HOST").expect("missing envvar host"); |
| 18 | + let user = env::var("MAILUSER").expect("missing envvar USER"); |
| 19 | + let password = env::var("PASSWORD").expect("missing envvar password"); |
| 20 | + let port = 993; |
| 21 | + |
| 22 | + if let Some(email) = fetch_inbox_top(host, user, password, port)? { |
| 23 | + println!("{}", &email); |
| 24 | + } |
| 25 | + |
| 26 | + Ok(()) |
| 27 | +} |
| 28 | + |
| 29 | +fn fetch_inbox_top(host: String, user: String, password: String, port: u16) -> Result<Option<String>, Box<dyn Error>> { |
| 30 | + // Setup Rustls TcpStream |
| 31 | + let stream = TcpStream::connect((host.as_ref(), port))?; |
| 32 | + let tls = RustlsConnector::default(); |
| 33 | + let tlsstream = tls.connect(&host, stream)?; |
| 34 | + |
| 35 | + // we pass in the domain twice to check that the server's TLS |
| 36 | + // certificate is valid for the domain we're connecting to. |
| 37 | + let client = imap::Client::new(tlsstream); |
| 38 | + |
| 39 | + // the client we have here is unauthenticated. |
| 40 | + // to do anything useful with the e-mails, we need to log in |
| 41 | + let mut imap_session = client |
| 42 | + .login(&user, &password) |
| 43 | + .map_err(|e| e.0)?; |
| 44 | + |
| 45 | + // we want to fetch the first email in the INBOX mailbox |
| 46 | + imap_session.select("INBOX")?; |
| 47 | + |
| 48 | + // fetch message number 1 in this mailbox, along with its RFC822 field. |
| 49 | + // RFC 822 dictates the format of the body of e-mails |
| 50 | + let messages = imap_session.fetch("1", "RFC822")?; |
| 51 | + let message = if let Some(m) = messages.iter().next() { |
| 52 | + m |
| 53 | + } else { |
| 54 | + return Ok(None); |
| 55 | + }; |
| 56 | + |
| 57 | + // extract the message's body |
| 58 | + let body = message.body().expect("message did not have a body!"); |
| 59 | + let body = std::str::from_utf8(body) |
| 60 | + .expect("message was not valid utf-8") |
| 61 | + .to_string(); |
| 62 | + |
| 63 | + // be nice to the server and log out |
| 64 | + imap_session.logout()?; |
| 65 | + |
| 66 | + Ok(Some(body)) |
| 67 | +} |
0 commit comments