【问题标题】:how to download an email attachment from gmail in python for a particular subject and date如何在 python 中从 gmail 下载特定主题和日期的电子邮件附件
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-10-21
    • 2022-11-24
    • 2016-09-12
    • 1970-01-01
    • 2014-03-18
    • 2010-09-25
    • 2019-08-04
    • 2011-04-09
    • 1970-01-01
    相关资源
    最近更新 更多