You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python实现仅下载最近5天收到的邮件附件

实现方法

你使用的Imbox库原生支持按收件时间筛选邮件,不需要遍历全部邮件再判断,只需要修改两处代码即可实现需求:

  1. 先计算当前时间往前推5天的日期
  2. 在调用mail.messages()时传入时间过滤参数,仅获取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)
# 新增:计算5天前的日期
five_days_ago = datetime.date.today() - datetime.timedelta(days=5)
# 传入date__gt参数筛选晚于5天前的邮件
messages = mail.messages(date__gt=five_days_ago) 

for (uid, message) in messages:
    mail.mark_seen(uid) # 可选,标记邮件为已读

    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()

补充说明

  • 如果存在时区偏差导致筛选结果不符合预期,可以自行调整five_days_ago的计算逻辑,比如用带时区的datetime对象替换当前的date对象即可
  • 参数date__gt的含义是筛选日期大于传入值的邮件,对应你需要的「最近5天内收到」的需求

内容的提问来源于stack exchange,提问作者tsukikosagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:24:03