无需下载即可获取 Gmail 附件文件名 [英] Get the Gmail attachment filename without downloading it
问题描述
我正在尝试从可能包含一些大附件(大约 30MB)的 Gmail 帐户中获取所有邮件.我只需要名称,而不是整个文件.我找到了一段代码来获取消息和附件的名称,但它会下载文件然后读取其名称:
I'm trying to get all the messages from a Gmail account that may contain some large attachments (about 30MB). I just need the names, not the whole files. I found a piece of code to get a message and the attachment's name, but it downloads the file and then read its name:
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
我必须每分钟执行一次,所以我无法下载数百 MB 的数据.我是网络脚本的新手,所以有人可以帮助我吗?我实际上并不需要使用 imaplib,任何 python 库都适合我.
I have to do this once a minute, so I can't download hundreds of MB of data. I am a newbie into the web scripting, so could anyone help me? I don't actually need to use imaplib, any python lib will be ok for me.
最好的问候
推荐答案
你可以指定 BODYSTRUCTURE
而不是获取 RFC822
的完整内容.
Rather than fetch RFC822
, which is the full content, you could specify BODYSTRUCTURE
.
来自 imaplib
的结果数据结构相当混乱,但您应该能够在不下载整个内容的情况下找到消息每个部分的文件名、内容类型和大小.
The resulting data structure from imaplib
is pretty confusing, but you should be able to find the filename, content-type and sizes of each part of the message without downloading the entire thing.
这篇关于无需下载即可获取 Gmail 附件文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!