stalwartlabs / mail-send

E-mail delivery library for Rust with DKIM support
https://docs.rs/mail-send/
Apache License 2.0
206 stars 21 forks source link

Sample Usage using XOAuth2 for SMTP Sending of Email #16

Closed LorenzoLeonardo closed 1 year ago

LorenzoLeonardo commented 1 year ago

Hello

Do you have a sample in your code that will successfully email using SMPT XOAUTH2?

Url and scopes used to get token.

    AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())?,
    TokenUrl::new("https://oauth2.googleapis.com/token".to_string())?,

    Scope::new("https://www.googleapis.com/auth/gmail.send".to_string()),
    Scope::new("email".to_string()),
    Scope::new("profile".to_string()),

This is the sample code I created

let auth_code_grant = AuthCodeGrant::new(
    ClientId::new(client_id.to_string()),
    client_secret,
let message = MessageBuilder::new()
    .from((sender_name.as_ref(), sender_email.as_ref()))
    .to(vec![(receiver_name.as_ref(), receiver_email.as_ref())])
    .subject("Microsoft - Test XOAUTH2 SMTP!")
    .html_body("<h1>Hello, world!</h1>")
    .text_body("Hello world!");

let credentials =
    Credentials::new_xoauth2(sender_email.as_ref(), access_token.secret().as_str());
log::info!("Authenticating SMTP XOAUTH2 Credentials....");
let email_connect = SmtpClientBuilder::new("smtp.gmail.com", 587)
    .implicit_tls(false)
    .credentials(credentials)
    .connect()
    .await;

match email_connect {
    Ok(mut result) => {
        log::info!("Sending SMTP XOAUTH2 Email....");
        let send = result.send(message).await;
        match send {
            Ok(_result) => {}
            Err(err) => {
                log::error!("SMTP Sending Error: {err:?}");
            }
        }
    }
    Err(err) => {
        log::error!("SMTP Connecting Error: {err:?}");
    }
}

But I got this error. AuthenticationFailed(Response { code: 535, esc: [5, 7, 8], message: "Username and Password not accepted. Learn more at\n https://support.google.com/mail/?p=BadCredentials p5-20020a1709028a8500b001ab0d815dbbsm2483183plo.23 - gsmtp" })

I there any lacking in building the email?

mdecimus commented 1 year ago

Hi,

The code looks fine. If you are using Gmail, you need to obtain an App password for your account, see https://support.google.com/accounts/answer/185833?hl=en. I haven't tried running an OAuth flow against Gmail and I am not sure if it is allowed by Google.

LorenzoLeonardo commented 1 year ago

Microsoft already fix their side, this is now working. Closing the issue.