我正在尝试使用Google Java API服务基于Gmail REST API发送邮件。我已经通过Google Developer Console配置了应用程序客户端并下载了p12和json文件。
我已经使用了这个示例程序:https://developers.google.com/gmail/api/guides/sending#sending_messages...
这个示例可以工作,但它是基于GoogleAuthorizationCodeFlow的。我想直接从服务器调用,而不是打开浏览器获得访问令牌... 我已经得到了(访问令牌),但最后我收到了“Bad Request”的错误信息...为什么???我没有收到更多的信息,只有“Bad Request”和“Precondition Failed”。
根据这个情况,我按照以下步骤进行:
第一步:基于我的客户端帐户邮件和生成的p12文件创建GoogleCredential对象:
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();
我需要指出的是,使用ClientID而不是ClientMail会导致很多问题。必须使用@developer.gserviceaccount.com帐户,而不是.apps.googleusercontent.com。如果您没有发送这些参数,则会收到“INVALID GRANT”错误。在此处进行了说明:https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization
第二步:基于凭据创建Gmail服务:
Gmail gmailService = new Gmail.Builder(httpTransport,
jsonFactory,
credential)
.setApplicationName(APP_NAME)
.build();
第三步 从MimeMessage创建一个Google原始消息:
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;
第四步 调用服务:
Message message = _createMessageWithEmail(email);
message = service.users()
.messages()
.send(userId,message)
.execute();
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)
有任何想法是哪里出了问题或是哪个前提条件失败了吗?