繁体   English   中英

下载最近 5 天在 Python 中收到的附件

[英]Download attachments received for the last 5 days in Python

我对 python 很陌生。 这是我正在使用的工作代码,但如何添加过滤器,其中仅扫描和下载最近 5 天的 email 附件。

提前致谢!

      import os
      from imbox import Imbox # pip install imbox
      import traceback
      import datetime
      
      host = "imap.gmail.com"
      username = "myemail@gmail.com"
      password = '*******'
      download_folder = "my/existing/dir"
      
      if not os.path.isdir(download_folder):
          os.makedirs(download_folder, exist_ok=True)
      
      mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
      # messages = mail.messages() # defaults to inbox
      
      for (uid, message) in messages:
          mail.mark_seen(uid) # optional, mark message as read
      
          for idx, attachment in enumerate(message.attachments):
              try:
                  att_fn = attachment.get('filename')
                  download_path = f"{download_folder}/{att_fn}"
                  print(download_path)
                  with open(download_path, "wb") as fp:
                      fp.write(attachment.get('content').read())
              except:
                  pass
                  print(traceback.print_exc())
      
      mail.logout()

在 IMAP 中无法直接通过附件进行搜索。 (*BODYSTRUCTURE 功能可以获取结构。)

你可以:

  1. 获取过去 5 天的电子邮件
  2. 分析其附件

代码:

import datetime
from imap_tools import MailBox, A

with MailBox('imap.mail.com').login('test@mail.com', 'pwd') as mailbox:
    for msg in mailbox.fetch(A(date_gte=datetime.date.today() - datetime.timedelta(days=5))):
        print(msg.uid, msg.subject)
        for att in msg.attachments:
            print(att.filename, len(att.payload))

https://github.com/ikvk/imap_tools我是作者。

暂无
暂无

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

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