【发布时间】:2019-03-06 09:25:22
【问题描述】:
我正在尝试下载 gmail 收件箱的附件形式,邮件每天都会收到,我必须从邮件中下载附件,我拥有的代码可以让我下载收件箱中的整个附件。 我想要的是下载那天特定邮件的附件表格。
我正在使用此代码:
导入电子邮件 导入getpass,imaplib 导入操作系统 导入系统
detach_dir = 'path'
# if 'attachments' not in os.listdir(detach_dir):
# os.mkdir('attachments')
userName = 'xyz@gmail.com'
passwd = 'xyzabc'
imapSession = imaplib.IMAP4_SSL('imap.gmail.com')
typ, accountDetails = imapSession.login(userName, passwd)
if typ != 'OK':
print ('Not able to sign in!')
raise
day = datetime.now().strftime("%Y-%m-%d")
subject = 'this is the subject name'
look_for = '(SENTSINCE {0} SUBJECT "{1}")'.format(datetime.strptime(day, '%Y-%m-%d').strftime('%d-%b-%Y'), subject)
imapSession.select('Inbox')
typ, data = imapSession.search(None, look_for)
if typ != 'OK':
print ('Error searching Inbox.')
raise
# Iterating over all emails
for msgId in data[0].split(): typ, messageParts = imapSession.fetch(msgId,'(RFC822)')
if typ != 'OK':
print ('Error fetching mail.')
raise
emailBody = messageParts[0][1]
mail = email.message_from_string(emailBody)
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
# print part.as_string()
continue
if part.get('Content-Disposition') is None:
# print part.as_string()
continue
fileName = part.get_filename()
if bool(fileName):
filePath = os.path.join(detach_dir,fileName)
if not os.path.isfile(filePath) :
print (fileName)
fp = open(filePath, 'wb')
print "done"
fp.write(part.get_payload(decode=True))
fp.close()
imapSession.close()
imapSession.logout()
这不是下载文件并关闭 plz 帮助解决代码,或者如果有人有它的代码,请在答案部分提供它
【问题讨论】:
-
调整搜索时间后,您的代码对我来说运行良好。您是否有理由搜索 SENTSINCE 什么是有效的 datetime.now ? FWIW,在创建 'imapSession' 之前添加 'imaplib.Debug = 4' 将允许您查看正在与服务器交换的内容,以防出现您不期望的返回(或不返回)。
-
我正在使用 sentsince,因为我必须收到今天的邮件,因为该邮件每天发送一次。您能否为此目的分享您的代码,以便我知道有什么区别。
-
我所做的更改是将日期硬编码为 '01-Jan-2010' 在 look_for 的 .format 部分...只是因为它比给自己发送带有特定测试的消息更容易主题和我可以验证的附件。
-
哦...我还预先创建了路径目录,因为那是您的 detach_dir。
-
可以分享一下代码吗?
标签: python python-2.7 gmail imap email-attachments