如何用python从gmail下载特定主题和日期的电子邮件附件
我正在尝试从gmail的收件箱下载附件。邮件每天都会来,我必须从邮件中下载附件。我的代码可以让我下载收件箱中的所有附件。 我想下载的是当天那封邮件的附件 我正在使用以下代码: 导入电子邮件 导入getpass,imaplib 导入操作系统 导入系统如何用python从gmail下载特定主题和日期的电子邮件附件,python,python-2.7,gmail,imap,email-attachments,Python,Python 2.7,Gmail,Imap,Email Attachments,我正在尝试从gmail的收件箱下载附件。邮件每天都会来,我必须从邮件中下载附件。我的代码可以让我下载收件箱中的所有附件。 我想下载的是当天那封邮件的附件 我正在使用以下代码: 导入电子邮件 导入getpass,imaplib 导入操作系统 导入系统 detach_dir = 'path' # if 'attachments' not in os.listdir(detach_dir): # os.mkdir('attachments') userName = 'xyz@gmail.co
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帮助,或者如果任何人有代码,请在回答部分给出
我的外部库
一旦我调整了搜索时间,你的代码对我来说运行良好。你现在搜索Sent有什么原因吗?FWIW,在创建“imapSession”之前添加“imaplib.Debug=4”将允许您查看与服务器交换的内容,以防有您不期望的内容返回(或不返回)。我使用sentsince是因为我必须获取今天的邮件,因为该邮件每天都会返回一次。你能分享一下你的代码吗?这样我就可以知道有什么区别了。我做的更改是在你的look_的.format部分将日期硬编码为'01-Jan-2010',只是因为这比给我自己发送一条带有某个测试主题的消息和一个我可以验证的附件更容易。哦…我还预先创建了路径目录,因为那是你的分离目录。你能分享代码吗?一旦我调整了搜索时间,你的代码对我来说很好。你现在搜索Sent有什么原因吗?FWIW,在创建“imapSession”之前添加“imaplib.Debug=4”将允许您查看与服务器交换的内容,以防有您不期望的内容返回(或不返回)。我使用sentsince是因为我必须获取今天的邮件,因为该邮件每天都会返回一次。你能分享一下你的代码吗?这样我就可以知道有什么区别了。我做的更改是在你的look_的.format部分将日期硬编码为'01-Jan-2010',只是因为这比给我自己发送一条带有某个测试主题的消息和一个我可以验证的附件更容易。哦…我还预先创建了路径目录,因为那是你的分离目录。你能分享代码吗?
from datetime import date
from imap_tools import MailBox, AND
# get list of emails that subject contains 'the key' and date is today from INBOX
# and save its attachments to files
with MailBox('imap.mail.com').login('test@mail.com', 'pwd', 'INBOX') as mailbox:
for msg in mailbox.fetch(AND(subject='the key', date=date.today())):
print(msg.date, msg.subject)
for att in msg.attachments:
print('-', att.filename)
with open('C:/1/{}'.format(att.filename), 'wb') as f: # *names may repeat!
f.write(att.payload)