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

如何用Python O365库通用检测不同来源的加密邮件?

检测O365账户收到的加密邮件的通用方法

你当前通过.rpmsg附件判断Outlook加密邮件的方法仅适用于特定场景,针对来自Gmail、Yahoo等任意服务商的加密邮件,以下是更通用的检测方案,优先基于Python O365库和邮件原生属性实现:

1. 利用O365库内置属性直接判断

新版O365库的Message对象封装了Microsoft Graph API返回的isEncrypted字段,可直接调用该属性快速判断:

from O365 import Account

# 假设已完成账户认证流程
account = Account(your_credentials)
mailbox = account.mailbox()
inbox = mailbox.inbox_folder()

for message in inbox.get_messages(limit=10):
    is_encrypted = message.is_encrypted
    print(f"主题: {message.subject}, 是否加密: {is_encrypted}")

注意:需确保O365库版本在2.0以上,且API权限包含Mail.Read。

2. 检查邮件头的加密标识

不同服务商的加密邮件会在邮件头中留下特定标记,可通过解析邮件头覆盖更多场景:

  • Exchange环境下的加密邮件会携带X-MS-Exchange-Organization-Encryption: True头
  • S/MIME加密邮件的Content-Type通常为application/pkcs7-mime或multipart/encrypted
  • 部分加密邮件的Content-Description会包含"Encrypted Message"关键字

示例代码:

def check_header_encryption(message):
    headers = message.headers
    # 检查Exchange加密标识
    if headers.get('X-MS-Exchange-Organization-Encryption') == 'True':
        return True
    # 检查内容类型
    content_type = headers.get('Content-Type', '')
    if 'application/pkcs7-mime' in content_type or 'multipart/encrypted' in content_type:
        return True
    # 检查内容描述
    if 'Encrypted Message' in headers.get('Content-Description', ''):
        return True
    return False

3. 扩展附件检测逻辑

除.rpmsg外,不同加密标准的邮件会携带其他类型附件:

  • .p7m:S/MIME加密的典型附件格式
  • 部分加密邮件会将加密内容封装为application/pkcs7-mime类型的附件

扩展后的附件检测函数:

def check_attachment_encryption(message):
    encrypted_extensions = ('.rpmsg', '.p7m')
    encrypted_content_types = ('application/pkcs7-mime', 'application/x-pkcs7-mime')
    
    for att in message.attachments:
        # 检查附件扩展名
        if att.name and att.name.lower().endswith(encrypted_extensions):
            return True
        # 检查附件内容类型
        if att.content_type in encrypted_content_types:
            return True
    return False

综合检测方案

将上述方法结合,最大化覆盖各种加密场景:

def is_encrypted(message):
    # 优先使用内置属性
    if hasattr(message, 'is_encrypted') and message.is_encrypted:
        return True
    # 检查邮件头
    if check_header_encryption(message):
        return True
    # 检查附件
    if check_attachment_encryption(message):
        return True
    return False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:17:27