I’m working as a Google Workspace admin and our organization uses Gmail for email services. I have a backend Java application that needs to send emails from a specific Gmail account like “[email protected]”. Currently, my app uses basic username and password authentication for SMTP.
Since Google is removing support for password-based authentication and moving to OAuth2, I need to update my implementation. The key thing is that my server application sends emails automatically without any user interaction. No real users will be authenticating through my app.
I found Google’s documentation about sending emails through Gmail API and there’s a Java sample called SendMessage.java. I think this might be what I need for my server-side email sending.
Is this the right approach for automated email sending from a server?
I’m confused about the OAuth setup process. From what I understand:
- Create a new project in Google API Console
- Generate OAuth credentials and download the client_secret.json file
- Use these credentials in my Java code
I have two main questions:
First, when creating OAuth credentials, it asks for a redirect URI. Since my use case doesn’t involve user interaction, do I still need to provide this?
Second, the sample code uses GoogleCredentials.getApplicationDefault() which reads from an environment variable. Is this the same file as the client_secret.json I download during setup?
Here’s my current email sending method that uses password authentication:
public void dispatchEmail(String targetAddress, String emailSubject, String messageBody) throws Exception {
String userPassword = config.getProperty(SMTP_AUTH_PASSWORD);
MimeMessage emailMessage = createEmailMessage(targetAddress, emailSubject, messageBody);
String smtpServer = config.getProperty(SMTP_SERVER_HOST);
try {
this.mailTransport.connect(smtpServer, this.fromAddress, userPassword);
this.mailTransport.sendMessage(emailMessage, emailMessage.getAllRecipients());
}
Any guidance on migrating this to OAuth2 would be helpful.