Sending emails from Java app with Gmail API

Paweł Świderski
1 min readMar 18, 2018

Sending emails from Java with using Gmail API is safer than any other method because it is less likely that your emails will be treated as SPAM and Google won’t block your application.

This article tells you how to implement sending emails from your Java app with using Gmail API. Article about authentication with google API is a prerequisite to follow instructions in this one. You need values of clientId, clientSecret, accessToken and refreshToken.

Application

Full code of the sample application is available on my GitHub:

To run the project in IDE (e.g. IntelliJ) install Lombok plugin and enable annotation processing.

Configure GmailCredentials

In main method of Main class there is a definition of GmailService that requires GmailCredentials to be able to operate. Implementation of GmailService you can find here.

https://github.com/pablo127/gmail-api-sample/blob/master/src/main/java/io/bitbucket/pablo127/gmail/Main.java

GmailCredentials takes:

  • userEmail — the gmail account that is used to send emails, authentication procedure has been performed on that account.
  • clientId
  • clientSecret
  • accessToken
  • refreshToken

ClientId, clientSecret and tokens are the ones that have been generated in the authentication procedure.

Summary

I hope you’ve learned something new.

If you have any questions or comments. Please let me know. Constructive feedback is appreciated.

--

--