Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example gmail_oauth2.rs #113

Open
incker opened this issue Nov 17, 2024 · 0 comments
Open

Example gmail_oauth2.rs #113

incker opened this issue Nov 17, 2024 · 0 comments

Comments

@incker
Copy link

incker commented Nov 17, 2024

Hello!
I have seen example here:
https://github.com/async-email/async-imap/blob/main/examples/src/bin/gmail_oauth2.rs

I was trying to run with rustls and I have received such error:

Error: invalid peer certificate: UnknownIssuer

Can you please make an exapmle for rustls. My code that leads to this error:

use std::sync::Arc;

use anyhow::Result;
use futures::StreamExt;
use tokio::net::TcpStream;
use tokio_rustls::rustls::{ClientConfig, RootCertStore};
use tokio_rustls::TlsConnector;

struct GmailOAuth2 {
    user: String,
    access_token: String,
}

impl async_imap::Authenticator for &GmailOAuth2 {
    type Response = String;

    fn process(&mut self, _data: &[u8]) -> Self::Response {
        format!(
            "user={}\x01auth=Bearer {}\x01\x01",
            self.user, self.access_token
        )
    }
}

use tokio_rustls::rustls::pki_types::ServerName;
use tokio_util::compat::TokioAsyncReadCompatExt;

#[tokio::main]
async fn main() -> Result<()> {
    let gmail_auth = GmailOAuth2 {
        user: String::from("user"),
        access_token: String::from("access_token"),
    };

    let domain = "imap.gmail.com";

    let port = 993;
    let socket_addr = (domain, port);
    let domain = ServerName::try_from(domain).unwrap();

    let tcp_stream = TcpStream::connect(socket_addr).await?;
    let tls = default_tls_connector();
    let tls_stream = tls.connect(domain, tcp_stream).await?;
    let client = async_imap::Client::new(tls_stream.compat());

    let mut imap_session = match client.authenticate("XOAUTH2", &gmail_auth).await {
        Ok(c) => c,
        Err((e, _unauth_client)) => {
            println!("error authenticating: {}", e);
            return Err(e.into());
        }
    };

    match imap_session.select("INBOX").await {
        Ok(mailbox) => println!("{}", mailbox),
        Err(e) => println!("Error selecting INBOX: {}", e),
    };

    {
        let mut msgs = imap_session.fetch("2", "body[text]").await.map_err(|e| {
            eprintln!("Error Fetching email 2: {}", e);
            e
        })?;

        while let Some(msg) = msgs.next().await {
            print!("{:?}", msg?);
        }
    }

    imap_session.logout().await?;
    Ok(())
}


pub fn default_tls_connector() -> TlsConnector {
    let mut root_cert_store = RootCertStore::empty();
    root_cert_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    let config = ClientConfig::builder()
        .with_root_certificates(RootCertStore::empty())
        .with_no_client_auth();
    let connector = TlsConnector::from(Arc::new(config));
    connector
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant