I'm trying to send mails based on Gmail REST API using google java api services. I have configured through Google Develover Console an application client and downloaded p12 and json files.
I have used this sample programs, https://developers.google.com/gmail/api/guides/sending#sending_messages...
This sample works, but this is based on GoogleAuthorizationCodeFlow. I want just to work from server-to-server, invoking directly, not opening a browser to get an access token... and I got it (the access token) but finally i receive a Bad Request.... Why??? I don't receive more info just than "Bad Request" and "Precondition Failed"
Based on this i follow the next steps:
First Step: Create a GoogleCredential object based on my client account mail and p12 generated file:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()) .setJsonFactory(new JacksonFactory()) .setServiceAccountId(serviceAccountUserEmail) .setServiceAccountScopes(scopes) .setServiceAccountPrivateKeyFromP12File( new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH)) .build();
Here i have to point that i had many issues for ussing ClientID instead of ClientMail. It must use @developer.gserviceaccount.com account instead of .apps.googleusercontent.com . If u don't send this params ok , u get an "INVALID GRANT" error. This is explained here: https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization
Second Step : Create the Gmail Service based on the credentials:
Gmail gmailService = new Gmail.Builder(httpTransport, jsonFactory, credential) .setApplicationName(APP_NAME) .build();
Third Step Create a Google raw message from a MimmeMessage:
private static Message _createMessageWithEmail(final 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;
}
Fourth Step Invoke the service:
Message message = _createMessageWithEmail(email); message = service.users() .messages() .send(userId,message) .execute();
- Fifth Step : Get Result after execution...Here i receive the exception:
Exception in thread "main"
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Bad Request",
"reason" : "failedPrecondition"
} ],
"message" : "Bad Request"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
Any idea what is wrong or which is the Precondition failed??