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

使用Python结合Imbox库从指定发件人未读邮件中提取附件求助

问题根因
  • 原代码中for (uid,message) in URmail and inbox_messages_frommymail的写法逻辑错误:Python中对两个迭代器使用and运算时,不会自动取两个查询结果的交集,只会返回第二个迭代器的内容,因此永远只会筛选来自指定发件人的所有邮件,不会叠加未读条件。
  • Imbox库的messages()方法原生支持同时传入多个筛选参数,无需分开查询再合并。
修复方案

直接将unread=True和发件人条件同时传入messages()方法即可实现双条件匹配,同时优化允许发件人匹配逻辑,支持所有在email-allowed.txt中配置的邮箱,后续新增允许发件人无需修改代码。

完整修复后代码
import os
from imbox import Imbox # pip install imbox
import traceback
from pathlib import Path

host = "imap.gmail.com"
download_folder = "/home/pi/download/folder"
path = '/home/pi/eink_picture_frame'
pwfile = Path(path+"/maillogin.pwd")   # 存储邮箱账号密码的文件

if pwfile.is_file():
    with open(pwfile,"r") as pf:
        pw_lines = [line.rstrip('\n') for line in pf]
    username = pw_lines[0]
    password = pw_lines[1]
else:
    print("请在'maillogin.pwd'文件中填写登录信息!\n第一行:邮箱账号\n第二行:密码")  
    quit()

allowfile = Path(path+"/email-allowed.txt")   # 存储允许的发件人邮箱的文件
allowed_senders = []
if allowfile.is_file():
    with open(allowfile,"r") as af:
         allowed_senders = [line.rstrip('\n') for line in af]
else:
    print("请在'email-allowed.txt'中添加允许的发件人邮箱!\n示例:\njoeshmo@aol.com\nuser@google.com")
    quit()

if not os.path.isdir(download_folder):
    os.makedirs(download_folder, exist_ok=True)
    
mailS = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
# 核心改动:匹配未读+允许列表内发件人的双条件邮件
target_messages = []
for uid, message in mailS.messages(unread=True):
    sender_email = message.sent_from[0]['email']
    if sender_email in allowed_senders:
        target_messages.append((uid, message))


for (uid,message) in target_messages:
    print(message)
    mailS.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:
            print(traceback.print_exc())

mailS.logout()
补充说明
  • 若使用Gmail邮箱,需要先在账号设置中开启IMAP服务,若开启了两步验证,需要使用应用专用密码登录。
  • 适配了多允许发件人的场景,后续新增发件人直接在email-allowed.txt中每行添加一个邮箱即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:06:00