2016-06-15 33 views
-1

我使用Gmail API從我的Gmail中檢索郵件。具體而言,在使用這個網址的Hangouts對話電子郵件:https://www.googleapis.com/gmail/v1/users/me/messages?q=in:chats從gmail api檢索內嵌圖像?

當我在消息進入,我看到這個結構

{ 
    "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\" <Oscarj[email protected]>" 
     } 
    ], 
    "body": { 
     "size": 2, 
     "data": "ZGY=" 
    } 
    }, 
    "sizeEstimate": 100 
} 

,你可以看到,機身的消息是「DF」。到目前爲止,一切都很好。

環聊消息是圖片時出現問題。 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\" <[email protected]>" 
     } 
    ], 
    "body": { 
     "size": 0, 
     "data": "" 
    } 
    }, 
    "sizeEstimate": 100 
} 

我需要檢索此內嵌圖像。任何幫助將不勝感激!

+0

你的問題到底是什麼?你問如何獲取圖像的網址? –

+0

對不起,是@WoodrowBarlow。編輯我的問題 –

+0

通過Gmail API獲取聊天消息[不支持](http://stackoverflow.com/questions/25316138/find-timestamp-for-hangout-and-chat-messages-retrieved-with-gmail-api ),所以獲取附件可能是不可能的。 – Tholle

回答

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(); 
} 
} 
} 
+0

謝謝,但問題是與環聊消息。它看起來是空的,沒有附件或任何東西。這適用於使用Gmail API檢索的正常電子郵件,但不適用於環聊消息。 –

0

僅供參考PHP的解決方案是與此類似: BASE64_DECODE(strtr函數的效率($ gmail->服務 - > users_messages_attachments->獲取( '我',$消息 - > id,$ arrPart ['body'] ['attachmentId']) - > data,'-_','+ /'));