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

如何用Python的imaplib获取指定邮件的所有附件名称?

获取邮件所有附件名称并保存为JSON文件

问题说明

仅使用imaplib库,获取指定邮件的所有附件名称并生成列表,将列表保存到JSON文件中,无需下载任何附件。当前使用的函数仅能返回单个附件名,无法收集所有附件。

原函数问题分析

原函数中filename是单个变量,遍历邮件部件时每次都会被覆盖,最终只能返回最后一个附件的名称;同时存在无需保留的下载逻辑,且HTML内容的获取逻辑有缺陷。

修改后的完整实现

import imaplib
import email
import json

def get_body_and_attachments(msg):
    email_body = None
    attachment_names = []  # 改为列表存储所有附件名
    html_part = None
    
    if msg.is_multipart():
        for part in msg.walk():
            content_type = part.get_content_type()
            content_disposition = str(part.get("Content-Disposition"))
            
            try:
                body = part.get_payload(decode=True).decode()
            except:
                body = None
            
            # 处理纯文本正文
            if content_type == "text/plain" and "attachment" not in content_disposition:
                email_body = body
            # 处理HTML正文
            elif content_type == "text/html" and "attachment" not in content_disposition:
                html_part = body
            # 收集附件名称,不下载附件
            elif "attachment" in content_disposition:
                fname = part.get_filename()
                if fname:  # 避免空文件名的情况
                    attachment_names.append(fname)
    else:
        # 非多部件邮件处理
        content_type = msg.get_content_type()
        try:
            body = msg.get_payload(decode=True).decode()
        except:
            body = None
        
        if content_type == "text/plain":
            email_body = body
        elif content_type == "text/html":
            html_part = body
    
    return email_body, attachment_names, html_part

# 示例:连接IMAP服务器并处理指定邮件
def fetch_attachments_and_save_json(imap_host, imap_user, imap_pass, mail_id):
    # 连接IMAP服务器
    imap = imaplib.IMAP4_SSL(imap_host)
    imap.login(imap_user, imap_pass)
    imap.select("INBOX")  # 选择收件箱,可根据需求修改
    
    # 获取指定邮件
    _, msg_data = imap.fetch(mail_id, "(RFC822)")
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            msg = email.message_from_bytes(response_part[1])
            _, attachment_names, _ = get_body_and_attachments(msg)
            
            # 保存附件列表到JSON文件
            with open("attachment_names.json", "w", encoding="utf-8") as f:
                json.dump(attachment_names, f, ensure_ascii=False, indent=4)
            print(f"附件列表已保存到attachment_names.json,共{len(attachment_names)}个附件")
    
    imap.close()
    imap.logout()

# 使用示例(替换为你的邮箱信息和邮件ID)
# fetch_attachments_and_save_json(
#     imap_host="imap.example.com",
#     imap_user="your_email@example.com",
#     imap_pass="your_password_or_app_password",
#     mail_id="1"  # 邮件的ID,可通过imap.search获取
# )

关键修改点

  • 将单个filename变量改为attachment_names列表,遍历过程中收集所有附件名称
  • 移除了下载附件的无关代码,仅保留获取文件名的逻辑
  • 修正了HTML正文的获取逻辑,确保能正确捕获非多部件邮件中的HTML内容
  • 增加了空文件名的判断,避免无效值加入列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:10:30