如何从python中的gmail下载gmail电子邮件附件以获取特定主题和日期

时间:2019-03-06 09:25:23

标签: 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.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来帮助您解决代码,或者如果有人拥有它的代码,请在答案部分中给出

1 个答案:

答案 0 :(得分:0)

我的外部库 https://github.com/ikvk/imap_tools

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)