从gmail api中检索内嵌图像?

时间:2016-06-15 19:59:53

标签: gmail-api

我使用Gmail API从Gmail中检索邮件。具体而言,使用此网址的环聊对话电子邮件:https://www.googleapis.com/gmail/v1/users/me/messages?q=in:chats

当我输入消息时,我看到了这个结构

 {
  "id": "1555561f7b8e1sdf56b",
  "threadId": "155552511dfsd83ce98",
  "labelIds": [
    "CHAT"
  ],
  "snippet": "df",
  "historyId": "270812",
  "internalDate": "1466016331704",
  "payload": {
    "partId": "",
    "mimeType": "text/html",
    "filename": "",
    "headers": [
      {
        "name": "From",
        "value": "\"Oscar J. Irún\" <Oscarjiv91@gmail.com>"
      }
    ],
    "body": {
      "size": 2,
      "data": "ZGY="
    }
  },
  "sizeEstimate": 100
}

正如您所看到的,正文消息是&#34; df&#34;。到目前为止,一切都还可以。

当环聊消息是图像时出现问题。 snippet字段为空,并且不会在邮件中显示任何附件。这是一个例子:

{
  "id": "155558233274d78c91",
  "threadId": "15fd5552511d83ce98",
  "labelIds": [
    "CHAT"
  ],
  "snippet": "",
  "historyId": "27sd0827",
  "internalDate": "1466018445133",
  "payload": {
    "mimeType": "text/html",
    "filename": "",
    "headers": [
      {
        "name": "From",
        "value": "\"Oscar J. Irún\" <Oscarjiv91@gmail.com>"
      }
    ],
    "body": {
      "size": 0,
      "data": ""
    }
  },
  "sizeEstimate": 100
}

我需要检索此内嵌图像。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

您可以使用Users.messages.attachments:get检索附件。请注意,此请求需要授权。所有对Gmail API的请求都必须由经过身份验证的用户授权。 Gmail使用OAuth 2.0协议对Google帐户进行身份验证并授权访问用户数据。

HTTP请求

GET https://www.googleapis.com/gmail/v1/users/userId/messages/messageId/attachments/id

public static void getAttachments(Gmail service, String userId, String messageId)
throws IOException {
Message message = service.users().messages().get(userId, messageId).execute();
List<MessagePart> parts = message.getPayload().getParts();
for (MessagePart part : parts) {
if (part.getFilename() != null && part.getFilename().length() > 0) {
String filename = part.getFilename();
String attId = part.getBody().getAttachmentId();
MessagePartBody attachPart = service.users().messages().attachment().
get(userId, messageId, attId).execute();
byte[] fileByteArray = Base64.decodeBase64(attachPart.getData());
FileOutputStream fileOutFile =
new FileOutputStream("directory_to_store_attachments" + filename);
fileOutFile.write(fileByteArray);
file OutFile.close();
}
}
}

答案 1 :(得分:0)

仅供参考,对于PHP,解决方案与此类似: base64_decode(strtr($ gmail-&gt; service-&gt; users_messages_attachments-&gt; get(&#39; me&#39;,$ message-&gt; id,$ arrPart [&#39; body&#39;] [&# 39; attachmentId&#39;]) - &gt;数据,&#39; -_&#39;,&#39; + /&#39;));

相关问题