使用Gmail API以html格式检索电子邮件/邮件正文

时间:2014-06-26 10:35:06

标签: python gmail-api

有没有办法使用GMail api以html格式检索邮件正文?

我已经浏览了message.get个文档。试图将format参数更改为fullminimal& raw。但它没有帮助。它返回了邮件正文的明文。


格式值说明:

" full":返回有效内容字段中已解析的电子邮件内容,并且不使用原始字段。 (默认)

" minimal":仅返回电子邮件元数据(如标识符和标签),它不会返回电子邮件标题,正文或有效内容。

" raw":以字符串形式返回原始字段中的整个电子邮件内容,并且不使用有效内容字段。这包括标识符,标签,元数据,MIME结构和小体部分(通常小于2KB)。


我们不能简单地以html格式获取邮件正文,还是有其他方法可以做到这一点,以便当他们在我的应用或GMail中看到邮件时,屏幕上显示的邮件差别很小?

3 个答案:

答案 0 :(得分:18)

具有HTML和纯文本内容的电子邮件将具有多个有效负载部分,而具有mimeType“text / html”的部分将包含HTML内容。您可以使用以下逻辑找到它:

var part = message.parts.filter(function(part) {
  return part.mimeType == 'text/html';
});
var html = urlSafeBase64Decode(part.body.data);

答案 1 :(得分:6)

FULL和RAW都会根据您的喜好返回任何text / html部分。如果你使用FULL,你将获得一个解析的表示,它将是嵌套的json词典,你必须走过来寻找text / html部分。如果您选择RAW格式,您将在Message.raw字段中以RFC822格式获取整个电子邮件。你可以用你选择的语言将它传递给mime库,然后使用它来找到你感兴趣的部分.Mime很复杂,你可能会有一个顶级" multipart&#34 ;键入text / html作为它的直接子项之一,但没有保证,它是一个任意深度的树结构! :)

答案 2 :(得分:0)

这是完整的教程:

1-假设您已经完成了所有凭据的创建here

2-这是您检索Mime消息的方式:

 public static String getMimeMessage(String messageId)
            throws Exception {

           //getService definition in -3
        Message message = getService().users().messages().get("me", messageId).setFormat("raw").execute();

        Base64 base64Url = new Base64(true);
        byte[] emailBytes = base64Url.decodeBase64(message.getRaw());

        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

        return getText(email); //getText definition in at -4
    }

3-这是创建Gmail实例的片段:

private static Gmail getService() throws Exception {
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    // Load client secrets.
    InputStream in = SCFManager.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();
    Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");

    return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}

4-这是解析Mime消息的 SECRET SAUCE

 public static String getText(Part p) throws
            MessagingException, IOException {
        if (p.isMimeType("text/*")) {
            String s = (String) p.getContent(); 
            return s;
        }

        if (p.isMimeType("multipart/alternative")) {
            // prefer html text over plain text
            Multipart mp = (Multipart) p.getContent();
            String text = null;
            for (int i = 0; i < mp.getCount(); i++) {
                Part bp = mp.getBodyPart(i);
                if (bp.isMimeType("text/plain")) {
                    if (text == null) {
                        text = getText(bp);
                    }
                    continue;
                } else if (bp.isMimeType("text/html")) {
                    String s = getText(bp);
                    if (s != null) {
                        return s;
                    }
                } else {
                    return getText(bp);
                }
            }
            return text;
        } else if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                String s = getText(mp.getBodyPart(i));
                if (s != null) {
                    return s;
                }
            }
        }

        return null;
    }

5-如果您想知道如何获取电子邮件ID,可以通过以下方式列出它们:

 public static List<String> listTodayMessageIds() throws Exception {
        ListMessagesResponse response = getService()
                .users()
                .messages()
                .list("me") 
                .execute();  

        if (response != null && response.getMessages() != null && !response.getMessages().isEmpty()) {
            return response.getMessages().stream().map(Message::getId).collect(Collectors.toList());
        } else {
            return null;
        }
    }

注意:

如果在此之后您想以“ Java脚本方式”查询该html正文,则建议您探索jsoup库。非常直观且易于使用:

Document jsoup = Jsoup.parse(body);

Elements tds = jsoup.getElementsByTag("td");
Elements ps = tds.get(0).getElementsByTag("p");

我希望这对其他有类似问题的人有所帮助:-)

相关问题