【发布时间】:2020-08-20 08:13:04
【问题描述】:
我从事学生项目,我必须使用 GMAIL API (Java) 连接到邮件服务器、获取新邮件并下载附件(如果有)。我已经用 JavaMail API 做到了,但是应该使用应用程序的邮件服务器不接受 IMAP 和 POP3 协议,它有自己的网络服务.
我有两个问题。
即使在 eclipse 中启动项目,我也遇到了麻烦。 首先,我不知道如何建立与邮件服务器的连接(例如 gmail 帐户)以及如何提供用户名和密码。我看到用于授权的 gmail api 使用 Oauth2。
第二个可能更容易解决。建立与邮件服务器的连接后,如何获取看不见的邮件并下载附件?
我想我可以自己完成第二部分,但没有 连接它甚至没有用尝试。 我看了几天官方文档,很困惑。
(如果你有一些代码示例或类似的例子会很好)
编辑 1:
完成了,现在我有这个错误
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
setAccessType 在 com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder
中找不到来自Quickstart 的所有导入都在那里。
编辑 2:
我现在很迷茫
Exception in thread "main" java.io.FileNotFoundException: Resource not found: /resources/credentials.json
行:
private static final String CREDENTIALS_FILE_PATH = "/resources/credentials.json";
当我检查System.out.print(System.getProperty("user.dir"));时
我收到F:\NBS\eclipse\FetchMail
编辑 3:
删除所有文件并重新开始,但eclipse仍然看起来很盲目 File not found
编辑 4:
在 Main 方法中测试方法 .getResourceAsStream(path) 并在 \eclipse\FetchMail 或我想要的任何其他文件中找到 credential.json
然后将文件移动到\eclipse\FetchMail\resources 并调用.getResourceAsStream("/resources/credentials.json") 也找到文件。
但是当在Quickstart 的getCredentials 方法中尝试这个时,有FileNotFound exception。
private static final String CREDENTIALS_FILE_PATH = "/resources/credentials.json";
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = Main.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
【问题讨论】:
-
你试过Quickstart吗?与服务器的授权和身份验证就像在完成前面的步骤后复制粘贴代码一样简单。它也有一个邮件列表。您应该为附件下载任务打开一个新帖子。如果您对代码有特定问题,我建议您尝试快速入门并返回。
-
我试过了,但我卡在了 credentials.json 上。 . i.ibb.co/mbJyzZV/download.png">我应该如何为这个客户分配电子邮件地址和密码?
标签: java eclipse email oauth-2.0 gmail-api