【问题标题】:How do I download attachments from gmail?如何从 gmail 下载附件?
【发布时间】:2022-08-24 13:32:23
【问题描述】:

编辑:我想出了答案,对于那些对此感到好奇的人是我的解决方案:

        for part in email_message.walk():
            if part.get_content_type() == \"application/json\":
                fname = part.get_filename()
                print(\"saving file\")
                with open(fname,\'wb\') as f:
                    f.write(part.get_payload(decode=True))

问题:

我能够使用以下方法找到我想从附件下载的 JSON 文件:

part.get_content_type() == \"application/json\"

但是不知道如何实际下载并将其保存到本地目录,有人可以帮忙吗?

这是整个方法:

#based on Python example from 
#https://github.com/codingforentrepreneurs/30-Days-of-Python/blob/master/tutorial-reference/Day%209/inbox.py

import imaplib

host = \'imap.gmail.com\' #inbox

def get_inbox(tempList):
    mail = imaplib.IMAP4_SSL(host)                                      #server
    mail.login(tempList[0], tempList[2])                                #login user name, user pass
    mail.select(\"inbox\")                                                #defualt inbox
    
    _, search_data = mail.search(None, \'UNSEEN\')                       
    my_message = []
    
    for num in search_data[0].split():                                  
        email_data = {}
        _, data = mail.fetch(num, \'(RFC822)\')                           #getting the msg data from gmail
        _, b = data[0]                                                  #data in bytes
        
        email_message = email.message_from_bytes(b)                     

        
        for part in email_message.walk():
            if part.get_content_type() == \"application/json\":
                pass
                           
        my_message.append(email_data)
    
    return my_message
  • 这不是一个问题?!?
  • 是的,但没有人回复,我想出了答案,所以请注意为遇到同样问题的人发布解决方案

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


【解决方案1】:
        for part in email_message.walk():
        if part.get_content_type() == "application/json":
            fname = part.get_filename()
            print("saving file")
            with open(fname,'wb') as f:
                f.write(part.get_payload(decode=True))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-08
    • 2016-03-02
    • 1970-01-01
    • 2016-02-22
    • 2016-09-12
    • 2016-04-22
    • 2022-11-11
    • 2015-10-25
    相关资源
    最近更新 更多