【发布时间】:2015-06-02 09:13:42
【问题描述】:
我正在尝试使用 google java api 服务基于 Gmail REST API 发送邮件。我已经通过 Google 开发者控制台配置了一个应用程序客户端并下载了 p12 和 json 文件。
我用过这个示例程序,https://developers.google.com/gmail/api/guides/sending#sending_messages...
此示例有效,但它基于 GoogleAuthorizationCodeFlow。我只想从服务器到服务器工作,直接调用,而不是打开浏览器来获取访问令牌......我得到了它(访问令牌)但最后我收到了一个错误的请求......为什么? ?除了“错误请求”和“先决条件失败”
,我没有收到更多信息基于此,我遵循以下步骤:
-
第一步:根据我的客户帐户邮件和 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(); -
第三步从 MimmeMessage 创建 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(); - 第五步:执行后获取结果...这里我收到异常:
线程“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)
知道什么是错误的或先决条件失败了吗?
【问题讨论】:
-
你有没有发现哪里出了问题?我有同样的问题。
标签: java rest google-cloud-endpoints gmail-api