获取Gmail附件文件名而不下载

mop*_*iok 12 python gmail attachment imaplib

我正在尝试从Gmail帐户中获取可能包含一些大附件(大约30MB)的所有邮件.我只需要名字,而不是整个文件.我找到了一段代码来获取消息和附件的名称,但它会下载文件然后读取其名称:

import imaplib, email

#log in and select the inbox
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('username', 'password')
mail.select('inbox')

#get uids of all messages
result, data = mail.uid('search', None, 'ALL') 
uids = data[0].split()

#read the lastest message
result, data = mail.uid('fetch', uids[-1], '(RFC822)')
m = email.message_from_string(data[0][1])

if m.get_content_maintype() == 'multipart': #multipart messages only
    for part in m.walk():
        #find the attachment part
        if part.get_content_maintype() == 'multipart': continue
        if part.get('Content-Disposition') is None: continue

        #save the attachment in the program directory
        filename = part.get_filename()
        fp = open(filename, 'wb')
        fp.write(part.get_payload(decode=True))
        fp.close()
        print '%s saved!' % filename
Run Code Online (Sandbox Code Playgroud)

我必须每分钟做一次,所以我无法下载数百MB的数据.我是网络脚本的新手,所以有人可以帮助我吗?我实际上不需要使用imaplib,任何python lib对我都没问题.

最好的祝福

rhe*_*ttg 9

RFC822您可以指定,而不是获取,即完整内容BODYSTRUCTURE.

由此产生的数据结构imaplib非常混乱,但您应该能够找到消息的每个部分的文件名,内容类型和大小,而无需下载整个内容.