Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Error getting access token for service account: 400 Bad Request

I'm using the Gmail API in my Android Java app with a service account to send emails programmatically. I've created a service account in my Google console and given Domain-wide delegation with the 'https://www.googleapis.com/auth/gmail.send' scope. I've added OAuth 2.0 Client IDs for my debug, release and production apps. I've also made the service account twice (in case I did something wrong the first time), changed the name of the JSON file to 'credentials.json' and added it to my project's raw folder. But I've been getting the same error, regardless. I've also checked the name of my service account against my code (PII Removed by Staff) and it's the same.  Below is the error I am getting:

IOException: Error getting access token for service account: 400 Bad Request
POST https://oauth2.googleapis.com/token
{"error":"invalid_grant","error_description":"Invalid grant: account not found"}, iss: offtodo@slottey-9b376.iam.gserviceaccount.com
E [sendEmail] error: java.io.IOException: Error getting access token for service account: 400 Bad Request
POST https://oauth2.googleapis.com/token

I've been stuck in this for three days with no luck. Any help would be much appreciated. Below is my java code:

public synchronized Message sendMail(Context context, String subject, String body, String senderAddress, String senderName, String replyTo, String recipients)  {
Log.i("SendMail","initiate...");
Log.i("SendMail","sendEmail to "+recipients);

try {
InputStream is = context.getResources().openRawResource(R.raw.credentials);


GoogleCredentials credentials = GoogleCredentials.fromStream(is)
.createScoped("https://www.googleapis.com/auth/gmail.send")
.createDelegated("jehani@mabs.lk");
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

// Create the gmail API client
Gmail service = new Gmail.Builder(new NetHttpTransport(),
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("Offtodo")
.build();


Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.setFrom(new InternetAddress(senderAddress));
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(recipients));
email.setSubject(subject);
email.setText(body);

// Encode and wrap the MIME message into a gmail message
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
email.writeTo(buffer);
byte[] bytes = buffer.toByteArray();
String encodedEmail = Base64.getUrlEncoder().encodeToString(bytes);
Message message = new Message();
message.setRaw(encodedEmail);

try {
Log.i("SendMail", "Create send message...");
message = service.users().messages().send("me", message).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
return message;
} catch (GoogleJsonResponseException e) {
Log.e("SendMail", "GoogleJsonResponseException: " + e.getMessage());
GoogleJsonError error = e.getDetails();
if (error.getCode() == 403) {
Log.e("SendMail", "Unable to send message: " + e.getDetails());
} else {
throw e;
}
}

} catch (IOException e) {
Log.e("SendMail", "IOException: " + e.getMessage());
throw new RuntimeException(e);
} catch (MessagingException e) {
Log.e("SendMail", "MessagingException: " + e.getMessage());
throw new RuntimeException(e);
}


return null;
}

 

1 3 17.5K
3 REPLIES 3

Hello @mabspace ,

Based on the provided information, it seems that your concern is related to the service account's credentials and the authorization process. You may consider these recommendations to help with the issue:

  1. Checking the Service Account Name. Kindly double check the spelling of the Service Account name in your code if it matches with the Service Account in your Google Cloud Platform.
  2. Check the JSON File. Ensure the JSON file is correctly named as "credentials.json" and is added to the project's raw folder.
  3. Check the Service Account Scope. Kindly ensure that the service account has the correct scopes.
  4. Check the Service Account key. Make sure that the service account key is not expired or revoked.
  5. Check the Service Account Email. Make sure the service account email matches the one used in your code.

Hey were you able to resolve this. Even I am stuck with the same error. 

I am also getting the same error for Firebase push notifications. Any idea regarding this will be very helpful !!

Top Labels in this Space