How to set up OAuth2 authentication for Gmail SMTP?

Need help with Gmail SMTP OAuth2 setup

I’m switching from PLAIN authentication to OAuth2 with Gmail SMTP. I created a service account and JSON keys, but my implementation keeps failing. I modified my code to use different function and variable names, yet I still run into issues.

public class EmailSender {
  void sendEmail() throws Exception {
    InputStream keyFile = getClass().getClassLoader().getResourceAsStream("service-account.json");
    String accountEmail = "[email protected]";
    GoogleCredentials creds = ServiceAccountCredentials.fromStream(keyFile)
        .createScoped(Arrays.asList("https://mail.google.com/"));
    creds.refreshIfExpired();
    String accessToken = creds.getAccessToken().getTokenValue();

    Properties config = new Properties();
    config.put("mail.smtp.auth.mechanisms", "XOAUTH2");
    config.put("mail.smtp.starttls.enable", "true");

    Session mailSession = Session.getInstance(config);
    mailSession.setDebug(true);

    SMTPTransport transport = (SMTPTransport) mailSession.getTransport("smtp");
    transport.connect("smtp.gmail.com", 587, accountEmail, null);

    String authData = "user=" + accountEmail + "\001auth=Bearer " + accessToken + "\001\001";
    String encodedAuth = Base64.getEncoder().encodeToString(authData.getBytes());
    transport.issueCommand("AUTH XOAUTH2 " + encodedAuth, 235);
  }
}

However, when I run this code, I get a 555-5.5.2 syntax error. What could be wrong with my implementation, and how can I resolve this issue?

I’ve been down this road before, and it can be quite frustrating. One thing that helped me was making sure the service account had the necessary permissions. Check if it’s been added to the Google Workspace domain and has the required admin roles.

Another issue I encountered was with the token expiration. Make sure you’re handling token refresh correctly. You might want to implement a mechanism to check if the token is expired before each send attempt and refresh it if necessary.

Also, don’t forget to verify that your firewall or any security software isn’t blocking the connection. I once spent hours debugging only to realize my firewall was the culprit.

Lastly, if all else fails, Google’s documentation on OAuth 2.0 for SMTP can be a lifesaver. It’s quite detailed and might shed light on something you’ve overlooked.

I’ve encountered similar challenges with OAuth2 for Gmail SMTP. One crucial step often overlooked is ensuring the correct scope is used. Instead of ‘https://mail.google.com/’, try ‘https://www.googleapis.com/auth/gmail.send’. Additionally, verify that your service account has domain-wide delegation enabled if you’re sending on behalf of another user. Lastly, double-check that the email address you’re using matches the one associated with the service account. These adjustments might resolve your 555-5.5.2 syntax error. If issues persist, consider logging the full SMTP conversation for more detailed debugging information.

hey mike, i had similar issues. try using the gmail api instead of smtp. it’s easier to set up and more reliable. you’ll need to enable the api in google cloud console and use their client library. might save you some headaches!