0

I am trying to authenticate a service account to Google to send emails from a server application.

this is done by

private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

private static HttpTransport HTTP_TRANSPORT;

private static final List<String> SCOPES =
        Arrays.asList(GmailScopes.GMAIL_LABELS, GmailScopes.GMAIL_SEND);

        return new  GoogleCredential.Builder()
            .setTransport(HTTP_TRANSPORT)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId("xxxxxxxxxxxxxx.iam.gserviceaccount.com")
            .setServiceAccountScopes(SCOPES)
            .setServiceAccountPrivateKeyFromP12File(new File("C:/temp/google/secret.p12"))
            .build();

The server response I am getting is

com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad     Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Bad Request",
"reason" : "failedPrecondition"
 } ],
"message" : "Bad Request"
}

On my service account I have enabled the option "Enable G Suite Domain-wide Delegation"

Is the above the correct way to try and authenticate, or have i missed a step

DaImTo
  • 72,534
  • 21
  • 122
  • 346
user2168435
  • 632
  • 2
  • 9
  • 24
  • Did you grant the service account access to the domain account users emails? https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority – DaImTo Mar 03 '17 at 10:48
  • yes, the service account client id is enabled for Email (Read/Write/Send) https://mail.google.com/ – user2168435 Mar 03 '17 at 13:02
  • also get the same response of 400 for using a json file – user2168435 Mar 03 '17 at 13:28
  • return GoogleCredential.fromStream(new FileInputStream("C:/temp/google/Auto-818971b20f33.json")) .createScoped(GmailScopes.all()) ; – user2168435 Mar 03 '17 at 13:28
  • Based from this [thread](http://stackoverflow.com/questions/32591549/gmail-api-400-bad-request-when-trying-to-send-an-email-php-code), the user needs to grant your application access to act on behalf of them. For the [Bad Request](http://stackoverflow.com/questions/35019357/google-play-developer-api-query-purchase-token-returns-invalid-value/36290762#36290762), it indicates that the query was invalid. E.g., parent ID was missing or the combination of dimensions or metrics requested was not valid. You may also check this [link](http://stackoverflow.com/questions/29327846) and see if it helps. – abielita Mar 04 '17 at 11:12

0 Answers0