我正在尝试使用 Google API 客户端以及 Google App Engine 之上的 GMail API 来修改多个用户的 GMail 消息。
流程概述:用户向 webApp 发送请求,将消息添加到队列中。在此请求中,将检查 Gmail 帐户是否存在给定邮件。此消息随后将通过 cron 作业进行处理(用户无需发出另一个请求)。
我按照文档中如何使用API的示例,有以下两种方法:
private static GoogleClientSecrets getClientCredential() throws IOException {
return GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(Utils.class.getResourceAsStream("/client_secret.json")));
}
public static GoogleAuthorizationCodeFlow newFlow(final String userId) throws IOException {
return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
getClientCredential(), Collections.singleton(GmailScopes.GMAIL_MODIFY))
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.setApprovalPrompt("force")
.addRefreshListener(
new DataStoreCredentialRefreshListener(userId, DATA_STORE_FACTORY))
.build();
}
public static Gmail loadGmailClient(final String userId) throws IOException {
final Credential credential = newFlow(userId).loadCredential(userId);
return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APP_NAME)
.build();
}
这基本上应该让我可以离线访问用户的邮箱,从而允许我稍后在 cron 中处理给定的消息。
只要 userId
是 "me"
一切似乎都工作正常。
但是,在 cron 作业阶段,应该在用户不实际向 WebApp 发出请求的情况下进行修改,因此我无法使用 "me"
但必须使用用户ID。因此我开始使用UserServiceFactory.getUserService().getCurrentUser().getUserId()
如userId
在请求阶段并将此 ID 与 cron 作业数据存储在一起。
这样做时,我不断收到类似的错误
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Delegation denied for <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ffaf2fef6f3dffbf0f2fef6f1b1fcf0f2" rel="noreferrer noopener nofollow">[email protected]</a>",
"reason" : "forbidden"
} ],
"message" : "Delegation denied for <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3a323e36331f3b30323e3631713c3032" rel="noreferrer noopener nofollow">[email protected]</a>"
}
我不确定哪一部分不正确,“委托(delegate)”显然似乎凭据有问题,但委托(delegate)似乎是与 Google Apps 完全相关的其他内容?有人能指出我正确的方向吗?
最佳答案
因此,正确的方法是使用 userId
加载凭据,例如
final Gmail gmail = loadGmailClient('someuserIdFromAGMailUser');
但在查询时使用“me”
,因此 GMail API 使用给定用户的凭据,但仅用于查询/修改他/她自己的数据:
final Message message = gmail.users().messages().get("me", mailId).execute();
似乎用户没有对他/她自己的帐户进行委派,因此在这两种情况下使用 userId
都会出现委派被拒绝的错误。
关于java - 在一个 Web 应用程序中访问多个 GMail 用户的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27005718/