Python Gmail API:如何批量下载电子邮件附件和电子邮件?

时间:2021-06-24 04:33:45

标签: python python-3.x gmail gmail-api

我有以下代码,用于下载 Gmail 电子邮件及其附件。它返回它的附件。

    def gmailAPIDownloadAttachments(self, messageID, userID="me"):
        try:
            service = self.gmailAPIService
            self.GLogger.info("Attempting to download attachments from messageID (" +str(messageID)+ ")")
            message = self.gmailAPIGetFullMessage(messageID, userID=userID)
            if message is False:
                self.GLogger.error("Failed to extract message (" +str(messageID)+ ") for downloading attachments")
                return False
            attachmentList = list()
            payload = message['payload']
            if 'parts' in payload:
                parts = payload['parts']
                for part in parts:
                    if part['filename']:
                        if 'data' in part['body']:
                            data = part['body']['data']
                        else:
                            att_id = part['body']['attachmentId']
                            att = service.users().messages().attachments().get(userId=userID, messageId=messageID, id=att_id).execute()
                            data = att['data']
                        file_data = base64.urlsafe_b64decode(data.encode('UTF-8'))
                        filename = part['filename']
                        extSearch = filename.find('.')
                        if extSearch == -1:
                            ext = ""
                            partFileName = filename[0:extSearch]
                        else:
                            ext = filename[extSearch+1:]
                            partFileName = filename[0:extSearch]

                        theAttachment = Attachment(filename,partFileName, ext, file_data)
                        attachmentList.append(theAttachment)

            self.GLogger.info("Successfully downloaded attachments from messageID (" +str(messageID)+ ")")
            return(attachmentList)
        except:
            self.GLogger.error("Encountered an error while attempting to download email attacments from messageID (" +str(messageID)+ ")")
            tb = traceback.format_exc()
            self.GLogger.exception(tb)
            return False

我了解如何将获取消息转换为批处理。例如,这是批量获取消息的方式:

from apiclient.http import BatchHttpRequest
import json

batch = BatchHttpRequest()

#assume we got messages from Gmail query API
for message in messages:
    batch.add(service.users().messages().get(userId='me', id=message['id'],
                                             format='raw'))
batch.execute()
for request_id in batch._order:
    resp, content = batch._responses[request_id]
    message = json.loads(content)
    #handle your message here, like a regular email object

然而,附件方面似乎有逻辑和其他可能的提取,例如在这一部分:

att_id = part['body']['attachmentId']
att = service.users().messages().attachments().get(userId=userID, messageId=messageID, id=att_id).execute()
data = att['data']

如何有效地批量获取邮件及其附件?我希望能够一次快速获取多封电子邮件。

0 个答案:

没有答案