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

Python 2.7获取指定标题邮件的全部或最新附件问题

Python 2.7 实现指定标题邮件附件获取(含最新带附件邮件筛选)

Hey there, since you've got this working in Python 3.6, adapting it to 2.7 mostly boils down to handling string/byte encoding differences and adjusting the older email module APIs. Let's break this down step by step, with code examples tailored to 2.7:

核心差异说明

Python 2.7 treats strings as bytes by default, while 3.x separates str (unicode) and bytes. The email module also has minor API changes—here's how to work around them:

1. 邮箱连接与邮件搜索

First, use imaplib to connect to your mail server. When searching for emails matching your subject and date range, you need to properly encode the subject for IMAP (since IMAP uses UTF-8 for search terms):

import imaplib
import email
from email.header import decode_header
import datetime

# 配置信息
MAIL_SERVER = 'imap.example.com'
MAIL_USER = 'your_email@example.com'
MAIL_PASS = 'your_password'
TARGET_SUBJECT = 'Your Target Email Subject'
DAYS_BACK = 7  # 过去7天的邮件

# 计算起始日期(IMAP格式:DD-MMM-YYYY,比如 01-Jan-2024)
start_date = (datetime.datetime.now() - datetime.timedelta(days=DAYS_BACK)).strftime("%d-%b-%Y")

# 连接邮箱
mail = imaplib.IMAP4_SSL(MAIL_SERVER)
mail.login(MAIL_USER, MAIL_PASS)
mail.select('inbox')  # 选择收件箱

# 编码主题为IMAP可识别的格式
encoded_subject = imaplib.utf8_encode(TARGET_SUBJECT)[0]
# 构造搜索条件:过去N天 + 指定主题 + 带有附件
search_criteria = f'(SINCE "{start_date}" SUBJECT {encoded_subject} HASATTACH)'
result, data = mail.search(None, search_criteria)

2. 解析邮件与提取附件

In Python 2.7, the email.message.Message object's methods work a bit differently. We'll loop through matching emails, parse attachments, and track the latest one:

latest_email_date = None
latest_email_attachments = []

# 遍历所有符合条件的邮件ID
email_ids = data[0].split()
if not email_ids:
    print("No matching emails found with attachments.")
    mail.close()
    mail.logout()
    exit()

# 先获取所有邮件的内部日期,排序后取最新的
email_id_date = []
for e_id in email_ids:
    result, data = mail.fetch(e_id, '(INTERNALDATE)')
    # 解析内部日期(兼容部分2.7版本的时区处理)
    date_str = data[0].split('"')[1].rsplit(' ', 1)[0]
    email_date = datetime.datetime.strptime(date_str, "%d-%b-%Y %H:%M:%S")
    email_id_date.append((email_date, e_id))

# 按日期降序排序,最新的在最前面
email_id_date.sort(reverse=True, key=lambda x: x[0])

# 处理邮件(可选择只取最新,或遍历所有)
for email_date, e_id in email_id_date:
    result, data = mail.fetch(e_id, '(RFC822)')
    raw_email = data[0][1]
    msg = email.message_from_string(raw_email)  # 2.7专属解析方法

    # 提取附件
    attachments = []
    for part in msg.walk():
        # 跳过多部分容器
        if part.get_content_maintype() == 'multipart':
            continue
        # 跳过非附件内容
        if part.get('Content-Disposition') is None:
            continue
        
        # 解码文件名(处理编码后的中文/特殊字符)
        filename = part.get_filename()
        if filename:
            decoded_filename = decode_header(filename)
            filename_str = ""
            for s, encoding in decoded_filename:
                if encoding:
                    filename_str += s.decode(encoding)
                else:
                    filename_str += str(s)
            attachments.append((filename_str, part.get_payload(decode=True)))
    
    # 记录最新邮件的附件信息
    if not latest_email_date:
        latest_email_date = email_date
        latest_email_attachments = attachments
        print(f"Found latest email with attachments, date: {latest_email_date}")
    
    # 保存附件到本地
    for filename, payload in attachments:
        with open(filename, 'wb') as f:
            f.write(payload)
        print(f"Saved attachment: {filename}")

# 关闭邮箱连接
mail.close()
mail.logout()

关键适配点

  • 邮件解析: Python 2.7用email.message_from_string()而非3.x的message_from_bytes(),因为2.7中raw_email属于字节串类型的str。
  • 文件名解码: decode_header()返回(内容, 编码)元组,需手动转换编码确保文件名可读。
  • 日期兼容: 部分2.7版本不支持%z时区解析,所以这里去掉了时区部分,若需要可安装python-dateutil库增强解析能力。
  • 附件写入: 用wb模式写入,直接处理get_payload(decode=True)返回的字节串。

可选扩展

如果需要收集过去N天内所有符合条件的附件列表,只需把附件信息存入一个全局列表即可,不用在首次获取后停止遍历。


内容的提问来源于stack exchange,提问作者Matt W.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:59:21