'Download attachments received for the last 5 days in Python

I'm pretty new to python. Here's a working code I'm using but how do I add a filter wherein only the recent 5 days of email attachments will be scanned and downloaded.

Thanks in advance!

      import os
      from imbox import Imbox # pip install imbox
      import traceback
      import datetime
      
      host = "imap.gmail.com"
      username = "[email protected]"
      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()


Solution 1:[1]

There is no way to direct search by attachments in IMAP. (*The BODYSTRUCTURE feature can fetch stucture.)

You can:

  1. Fetch emails for the last 5 days
  2. Analyze its attachments

code:

import datetime
from imap_tools import MailBox, A

with MailBox('imap.mail.com').login('[email protected]', '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 I am author.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1