如何从Gmail API中获取用户的所有电子邮件内容?

时间:2014-12-05 00:47:07

标签: java email gmail-api

我正在制作一个应该使用Gmail API接收Gmail用户电子邮件的应用程序。但是,我必须收到每封电子邮件的数据,作为收到的内容,发件人,主题和日期。有没有人以前实现过这个?

按照Google上的部分,我只能获取ID和线程每个电子邮件ID:

public class GmailApiQuickstart {

// Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
private static final String SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
private static final String APP_NAME = "GmailApiQuickstart";
private static final String USER = "me";
// Path to the client_secret.json file downloaded from the Developer Console
private static final String CLIENT_SECRET_PATH = "c:/client_secret.json";

private static GoogleClientSecrets clientSecrets;

public void buscar() throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();

clientSecrets = GoogleClientSecrets.load(jsonFactory,  new FileReader(CLIENT_SECRET_PATH));

// Allow user to authorize via url.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
.setAccessType("online")
.setApprovalPrompt("auto").build();

String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
.build();
System.out.println("Please open the following URL in your browser then type"
               + " the authorization code:\n" + url);

// Read code entered by user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();

// Generate Credential using retrieved code.
GoogleTokenResponse responseT = flow.newTokenRequest(code)
.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential()
.setFromTokenResponse(responseT);

// Create a new authorized Gmail API client
Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(APP_NAME).build();

ListMessagesResponse response = service.users().messages().list(USER).setQ("vagas").execute();

List<Message> messages = new ArrayList<Message>();
while (response.getMessages() != null) {
  messages.addAll(response.getMessages());
  if (response.getNextPageToken() != null) {
    String pageToken = response.getNextPageToken();
    response = service.users().messages().list(USER).setQ("vagas")
        .setPageToken(pageToken).execute();
  } else {
    break;
  }
}

for (Message message : messages) {
    //Essa é a parte onde pega o ID e Thread ID
    //qual(ais) parâmetro(s) devo adicionar para pegar o que preciso???
    System.out.println(message.toPrettyString());
}
}

}

谢谢大家!

1 个答案:

答案 0 :(得分:0)

根据电子邮件的ID,您可以使用Users.messages资源的get方法获取内容。它返回JSON响应中的内容,发件人,主题和收到的日期,To,From字段。

获取邮件时,您可以为响应指定有效内容格式。 FULL(默认)格式返回有效内容字段中的整个已解析消息。 MINIMAL格式仅返回标识符和标签等元数据。 RAW格式将数据作为base64url编码的字符串返回到原始属性中。