我可以在没有用户交互的情况下进行 Gmail API 调用吗?

问题描述

目前我需要使用 Gmail API 来检查新到达的电子邮件的标签。在我的笔记本电脑上非常完美,我第一次启动程序(Java)需要手动授权,后续调用不需要用户交互。

此程序是 Gmail API 的快速入门示例代码 https://developers.google.com/gmail/api/quickstart/java

现在我需要这个程序在服务器上运行,以便我可以监控登陆状态。经过数十次尝试,服务器无法检测到我从笔记本电脑上传的令牌,并不断要求我打开重定向 URL 进行授权。

gmailLog.info("getCredentials start!");
InputStream in = GmailAPI.class.getResourceAsStream("/credentials.json");
if (in == null) {
   gmailLog.error("null input stream,credentials missing");
   throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,JSON_FACTORY,clientSecrets,SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new File("tokens")))
            .setAccessType("offline")
            .build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow,receiver).authorize("user");

授权发生在代码的最后一行。 然后会生成一个tokens文件夹,请点击此链接查看 file structure

如您所见,tokens 文件夹位于根路径下。我将令牌文件夹复制到同一位置的服务器,但仍然要求我重定向。我想知道这可能是因为 StoredCredential 文件包含我机器的信息,所以它与服务器机器不匹配。

这是否意味着我永远无法在没有用户输入的情况下在服务器上执行此操作?谢谢。另外,如果绝对需要 GSuite 帐户,我愿意付费并成为企业用户。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)