繁体   English   中英

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

[英]how to download an email attachment from gmail in python for a particular subject and date

我正在尝试下载附件表单 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()

这不是下载文件并关闭请帮助解决代码,或者如果有人有它的代码,请在答案部分给出

我的外部库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)  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM