Send Mail through Google API using Oauth 2.0 and Google Service account (for Server to Server applications).
Google Service Account:
OAUTH requires input user/password for authentication. This is not suitable for background service, So google provides the use of a Google service account to access Google Workspace (also known as G-suite account or Google administration account) email service without user interaction. Service account only works for Google Workspace users, it will not work for personal Gmail accounts.
The Below all Steps should be done in the Google Workspace account.
Example:
abc@gmail.com is not a Google Administration Account.
But abc@xyz.com is a Google Administration Account.
To Create Google Administration Account, go to the below link: workspace.google.com
Step 1: Create Google Project:
(project should be created with a Google Workspace/administration account/G-Suite account)
1)go to the below URL: https://console.cloud.google.com/projectcreate
click on create, and the project will be created.
Step 2: Enable Gmail API:
1)Click on “APIs and Services” section.
2)Then click on “+ Enabled APIs and Services” button on top.
3)Search for “Gmail API”:
4)Click on “Gmail API”:
5)Click on “ENABLE”
Step 3: Create a Service Account:
(Service Account should be created with Google Workspace/administration account)1)Click on this link: https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts?supportedpurview=project
2)Select the project which u created in step 1:
3)Click on “+CREATE SERVICE ACCOUNT” and Under “Service Account details” enter the details:
4)Under “Grant this service account access to the project” and Grant owner Access and click continue
5)leave the “Grant users access to service account” just click done.
Step 4: Create a Key for the service account:
1)Click on “service account” on the left panel and then click on the service account you created:
2) We will get like this after clicking on the service account:
3) Click on “Keys”:
4) Click on “ADD KEY” and then click on “Create New Key”.
5) And click on the key type “Json” and click “create”:
a Json file will be downloaded.
The downloaded file will have these details:
credentials.json:
{ "type": "service_account", "project_id": "projectname", "private_key_id": "***************************", "private_key": "-----BEGIN PRIVATE KEY-----\n*********************\n-----END PRIVATE KEY-----\n", "client_email": "****@named-projectname-78979.iam.gserviceaccount.com", "client_id": "*********************", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/****%40named-projectname-78979.iam.gserviceaccount.com" }
Step 5: Enable Domain-wide Delegation and Grant Permissions:
1)Click on this URL: https://admin.google.com/ac/accountchooser?continue=https://admin.google.com/
2)On the left panel click on “security” then on “Access and Data Control” and then on “API controls”
3) Scroll down, under “Domain wide delegation”, and click on “MANAGE DOMAIN WIDE DELEGATION”.
4) On Domain-wide delegation page,
click on “Add new” under “Client ID” and add the Client ID value which will be present in the JSON file generated in Step 4. Under “OAuth scopes” add https://www.googleapis.com/auth/gmail.send and click on “authorize”.
Steps 6: The final step, the coding part:
Java code:
"user@abc.com" should be any user of the administration of which the service account JSON is created and used in "credentials.json"
import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.List; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.Base64; import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.GmailScopes; import com.google.api.services.gmail.model.Message; import com.google.auth.Credentials; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; public class SendMailGoogleServiceAccounts { private static final String CREDENTIALS_FILE_PATH = "credentials.json"; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport(); private static final String APPLICATION_NAME = "AppName"; public static void main(String[] args) { try { sendMessage("anyEmailid@gmail.com", "user@abc.com", "TestMail By Codemummy","Test mail to test google service account"); } catch (MessagingException | IOException | GeneralSecurityException e) { System.out.println("error"); e.printStackTrace(); } } private static Credentials getCredentials(String CREDENTIALS_FILE_PATH) throws IOException { InputStream in = SendMailGoogleServiceAccounts.class.getResourceAsStream(CREDENTIALS_FILE_PATH); if (in == null) { throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); }
GoogleCredentials credentials = GoogleCredentials.fromStream(in).createDelegated("user@abc.com").createScoped(List.of(GmailScopes.GMAIL_SEND)); return credentials; } private static Gmail getGmailService() throws IOException, GeneralSecurityException { return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpCredentialsAdapter(getCredentials(CREDENTIALS_FILE_PATH))).setApplicationName(APPLICATION_NAME) .build(); } public static String sendMessage(String to, String from, String subject, String body) throws MessagingException, IOException, GeneralSecurityException { Gmail service = getGmailService(); MimeMessage email = createMimeMessage(to, from, subject, body); Message message = createMessageWithEmail(email); message = service.users().messages().send("me", message).execute(); System.out.println("Mail Sent using GoogleAPI.....Google Service Account and the "+"Message id: " + message.getId()); System.out.println(message.toPrettyString()); if (message.getId() != null) { return "success"; } else { return "fail"; } } private static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); email.writeTo(bytes); String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray()); Message message = new Message(); message.setRaw(encodedEmail); return message; } private static MimeMessage createMimeMessage(String to, String from, String subject, String body) { try { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(subject); // Send the actual HTML message, as big as you like message.setContent(body, "text/html"); return message; } catch (MessagingException ex) { System.out.println(ex); return null; } } }
output:
Mail Sent using GoogleAPI.....Google Service Account and the Message id: 184d232c8de0713b { "id" : "184d232c8de0713b", "labelIds" : [ "SENT" ], "threadId" : "184d232c8de0713b" }
No comments