java 如何在 Gmail 中获取完整的邮件正文?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28026099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:52:18  来源:igfitidea点击:

How to get full message body in Gmail?

javagmailgmail-api

提问by somebody

I want to get full message body. So I try:

我想获得完整的消息正文。所以我尝试:

Message gmailMessage = service.users().messages().get("me", messageId).setFormat("full").execute();

That to get body, I try:

为了得到身体,我尝试:

gmailMessage.getPayload().getBody().getData()

but result always null. How to get full message body?

但结果总是如此null。如何获取完整的消息正文?

回答by Tholle

To get the data from your gmailMessage, you can use gmailMessage.payload.parts[0].body.data. If you want to decode it into readable text, you can do the following:

要从您的 gmailMessage 中获取数据,您可以使用 gmailMessage.payload.parts[0].body.data。如果要将其解码为可读文本,可以执行以下操作:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(gmailMessage.payload.parts[0].body.data)));

回答by Hinotori

I tried this way, since message.getPayload().getBody().getParts() was always null

我试过这种方式,因为 message.getPayload().getBody().getParts() 总是 null

import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.StringUtils;

(...)

(...)

Message message = service.users().messages().get(user, m.getId()).execute();
MessagePart part = message.getPayload();
System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(part.getBody().getData())));

And the result is pure HTML String

结果是纯 HTML 字符串

回答by Yury Staravoitau

I found more interesting way how to resolve a full body message (and not only body):

我发现了更有趣的方法来解析完整的正文消息(而不仅仅是正文):

System.out.println(StringUtils.newStringUtf8(   Base64.decodeBase64 (message.getRaw())));

回答by Gerard Verbeek

If you have the message (com.google.api.services.gmail.model.Message) you could use the following methods:

如果您有消息 (com.google.api.services.gmail.model.Message),您可以使用以下方法:

public String getContent(Message message) {
    StringBuilder stringBuilder = new StringBuilder();
    try {
        getPlainTextFromMessageParts(message.getPayload().getParts(), stringBuilder);
        byte[] bodyBytes = Base64.decodeBase64(stringBuilder.toString());
        String text = new String(bodyBytes, StandardCharsets.UTF_8);
        return text;
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncoding: " + e.toString());
        return message.getSnippet();
    }
}

private void getPlainTextFromMessageParts(List<MessagePart> messageParts, StringBuilder stringBuilder) {
    for (MessagePart messagePart : messageParts) {
        if (messagePart.getMimeType().equals("text/plain")) {
            stringBuilder.append(messagePart.getBody().getData());
        }

        if (messagePart.getParts() != null) {
            getPlainTextFromMessageParts(messagePart.getParts(), stringBuilder);
        }
    }
}

It combines all message parts with the mimeType "text/plain" and returns it as one string.

它将所有消息部分与 mimeType "text/plain" 组合在一起,并将其作为一个字符串返回。

回答by Tal Avissar

here is the solution in c# code gmail API v1 to read the email body content:

这是在 c# 代码 gmail API v1 中读取电子邮件正文内容的解决方案:

  var request = _gmailService.Users.Messages.Get("me", mail.Id);
                request.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;

and to solve the data error

并解决数据错误

 var res = message.Payload.Body.Data.Replace("-", "+").Replace("_", "/");
 byte[] bodyBytes = Convert.FromBase64String(res);


 string val = Encoding.UTF8.GetString(bodyBytes);

回答by Tomasz TJ

Base on the @Tholle comment I've made something like that

根据@Tholle 的评论,我做了类似的事情

Message message = service.users().messages()
        .get(user, messageHolder.getId()).execute();

System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(
        message.getPayload().getParts().get(0).getBody().getData())));

回答by Zaheer

When we get full message. The message body is inside Parts.

当我们收到完整的消息时。消息正文在部件内。

This is an example in which message headers (Date, From, To and Subject) are displayed and Message Body as a plain text is displayed. Parts in Payload returns both type of messages (plain text and formatted text). I was interested in Plain text.

这是一个示例,其中显示消息标题(日期、发件人、收件人和主题)并显示纯文本形式的消息正文。Payload 中的部分返回两种类型的消息(纯文本和格式化文本)。我对纯文本感兴趣。

Message msg = service.users().messages().get(user, message.getId()).setFormat("full").execute();
// Displaying Message Header Information
for (MessagePartHeader header : msg.getPayload().getHeaders()) {
  if (header.getName().contains("Date") || header.getName().contains("From") || header.getName().contains("To")
      || header.getName().contains("Subject"))
    System.out.println(header.getName() + ":" + header.getValue());
}
// Displaying Message Body as a Plain Text
for (MessagePart msgPart : msg.getPayload().getParts()) {
  if (msgPart.getMimeType().contains("text/plain"))
    System.out.println(new String(Base64.decodeBase64(msgPart.getBody().getData())));
}