Friday, June 10, 2022

Send gmail using OAuth2 - Java

 1.

Login to https://console.cloud.google.com/ to create the project and the client_id, oauth consent screen...

2.

Run the oauth2.py to get the refresh token.

I updated the file to support python 3.

3.

From Java,

call the below to exchange back the access token:

public static String getNewToken(String refreshToken, String clientId, String clientSecret) throws IOException {

List<String> scopes = new ArrayList<>();

TokenResponse tokenResponse = new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(),

refreshToken, clientId, clientSecret).setScopes(scopes).setGrantType("refresh_token").execute();

return tokenResponse.getAccessToken();

}

4. With the access token, call the below to send email:

SMTPTransport transport = new SMTPTransport(session, null);

transport.connect(SMTP_SERVER_HOST, FROM_USER_EMAIL, null);

transport.issueCommand(

"AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(

String.format("user=%s\1auth=Bearer %s\1\1", FROM_USER_EMAIL, newAccessToken).getBytes())),

235);

transport.sendMessage(msg, msg.getAllRecipients());

Refer:

https://hellokoding.com/sending-email-through-gmail-smtp-server-with-java-mail-api-and-oauth-2-authorization/

https://www.youtube.com/watch?v=-rcRf7yswfM

No comments:

Post a Comment