下载最近5天收到的附件(使用Python

Download attachments received for the last 5 days in Python(下载最近5天收到的附件(使用Python)
本文介绍了下载最近5天收到的附件(使用Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是个新手。这是我正在使用的工作代码,但我如何添加一个筛选器,以便只扫描和下载最近5天的电子邮件附件。

提前谢谢!

      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 我是作者。

这篇关于下载最近5天收到的附件(使用Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)