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

如何使用Python获取电子邮件的响应时间?

如何用Python获取电子邮件的响应时间

获取邮件响应时间的核心是找到回复邮件与原始邮件的关联关系,再计算两者的发送时间差。以下是基于imap_tools的可行方案:

关键思路

邮件对话的关联依赖邮件头中的两个字段:

  • In-Reply-To:回复邮件会包含此字段,值为原始邮件的Message-ID
  • References:部分邮件会包含此字段,记录对话中的所有关联邮件ID

我们需要:

  1. 连接IMAP邮箱,获取目标邮件列表
  2. 从回复邮件中提取In-Reply-To对应的原始邮件ID
  3. 查找原始邮件,获取两者的发送时间
  4. 计算时间差

代码实现

from imap_tools import MailBox, AND
from datetime import datetime
import email.utils

# 邮箱配置
IMAP_SERVER = 'imap.example.com'  # 替换为你的IMAP服务器,比如imap.gmail.com
USERNAME = 'your_email@example.com'
PASSWORD = 'your_password'  # 若为Gmail需用应用专用密码

def parse_email_date(date_str):
    """将邮件头的日期字符串转为datetime对象"""
    parsed_date = email.utils.parsedate_to_datetime(date_str)
    return parsed_date.replace(tzinfo=None)  # 统一转为无时区对象便于计算

with MailBox(IMAP_SERVER).login(USERNAME, PASSWORD, initial_folder='INBOX') as mailbox:
    # 获取所有邮件(可根据条件过滤,比如按日期、发件人)
    all_emails = list(mailbox.fetch(AND(all=True), headers=['Message-ID', 'Date', 'In-Reply-To']))
    
    # 构建邮件ID到邮件对象的映射
    email_id_map = {msg.headers.get('Message-ID'): msg for msg in all_emails if msg.headers.get('Message-ID')}
    
    # 遍历带回复标记的邮件,计算响应时间
    for msg in all_emails:
        in_reply_to = msg.headers.get('In-Reply-To')
        if not in_reply_to:
            continue  # 跳过非回复邮件
            
        original_msg = email_id_map.get(in_reply_to.strip('<>'))  # 去除Message-ID的<>包裹
        if not original_msg:
            print(f"未找到原始邮件: {in_reply_to}")
            continue
            
        # 解析时间并计算差
        reply_time = parse_email_date(msg.headers.get('Date'))
        original_time = parse_email_date(original_msg.headers.get('Date'))
        response_delta = reply_time - original_time
        
        print(f"邮件主题: {msg.subject}")
        print(f"原始邮件发送时间: {original_time}")
        print(f"回复邮件发送时间: {reply_time}")
        print(f"响应时间: {response_delta}\n")

注意事项

  • 部分邮件的In-Reply-To可能包含多个ID,或者格式不规范,需要额外处理字符串清洗
  • 若邮箱中的原始邮件已被删除,会无法找到对应邮件,需添加异常处理
  • 不同邮箱的IMAP服务器地址不同:比如QQ邮箱是imap.qq.com,Outlook是imap.outlook.com
  • 若使用Gmail,需开启IMAP并使用应用专用密码(两步验证开启时)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:45:50