2016-06-07 84 views
0

代码在JavaEE服务器(Wildfly)上运行,并在Linux OS(不带GUI的Raspbian)上运行。我想在后台进程中访问Gmail API,但他总是问我“请在浏览器中打开以下地址:....”。我能以某种方式防止这种情况吗以编程方式在后台Java进程中访问Google API授权

InputStream in = XmlServiceImpl.class 
     .getResourceAsStream("/mail.connector/client_secret.json"); 
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(DATA_STORE_FACTORY) 
     .setAccessType("offline").setApprovalPrompt("force").build(); 
Credential credential = new AuthorizationCodeInstalledApp(flow, 
     new LocalServerReceiver()).authorize("user"); 

try { 
    HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); 
    DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); 
} catch (Throwable t) { 
    t.printStackTrace(); 
    System.exit(1); 
} 

Credential credential = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) 
     .setApplicationName(APPLICATION_NAME).build(); 

Gmail service = null; 
try { 
    service = getGmailService(); 
} catch (IOException e1) { 
    // TODO Exception Handling 
    e1.printStackTrace(); 
} 

ListMessagesResponse response = null; 
try { 
    response = service.users().messages().list(USER_ID) 
      .setIncludeSpamTrash(true).execute(); 
} catch (IOException e) { 
    // TODO Exception Handling 
    e.printStackTrace(); 
} 
+0

授权必须通过浏览器至少进行一次。对于以后的登录,您可以存储令牌/凭证并在需要时访问它们。你的情况很新颖,但我认为如果你使用服务帐户会更好。 –

+0

但是,我可以通过服务帐户访问Gmail邮件吗?我没有收到“Google for Works”帐户。 –

+0

我怀疑您是否可以通过服务帐户访问Gmail。您可以使用Google云端硬盘,因为您可以与服务帐户共享文件夹和文档。 –

回答

0

我用JavaMailAPI从我的GMail帐户读取邮件。见Link

完美的作品。

相关问题