Files
syops/backend/app/services/shipping_notice/eml_parse.py
T
hugo 1b6483a4ea feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
2026-08-20 20:23:10 +08:00

1648 lines
60 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
services/shipping_notice/eml_parse.py
用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、附件目录,按模式可选附件全文)。
依赖:标准库 email/html、BeautifulSoup;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。
逻辑:由 notice_upload.extract_notice_text 在 file_type=eml 时调用;忽略内嵌图片/签名图;
嵌套 message/rfc822 与附件型 multipart(disposition/filename)登记为独立附件;
外层 body 不穿透 rfc822 / 附件型 multipart,避免订单文本误入正文或重复;
单附件失败不影响其余附件;总大小:顶层容器计费,展开子内容不计费;
附件摘要内存字段 `_payload_bytes` 供阶段二派生 FileAsset,写库/API 前须剥离。
"""
from __future__ import annotations
import hashlib
import html as html_lib
import re
import tempfile
from dataclasses import dataclass, field
from email import policy
from email.message import Message
from email.parser import BytesParser
from email.utils import parsedate_to_datetime
from pathlib import Path
from typing import Any, Callable, Literal
from bs4 import BeautifulSoup, Comment
# 签名/Logo 文件名启发式(仅对 image/* 生效)
_SIGNATURE_LOGO_NAME_RE = re.compile(
r"(?:^|[_.\-])(logo|signature|sig|banner|icon|spacer|pixel|footer|header)(?:[_.\-]|$)",
re.IGNORECASE,
)
_HTML_TABLE_TAGS = frozenset({'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td'})
_HTML_DROP_TAGS = frozenset({'script', 'style', 'img', 'svg', 'object', 'embed', 'iframe', 'template'})
_EML_PREVIEW_TAGS = frozenset({
'html', 'body', 'div', 'p', 'span', 'br', 'hr', 'blockquote', 'pre',
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'strong', 'b', 'em', 'i', 'u',
})
_EML_PREVIEW_STYLE_PROPERTIES = frozenset({
'background',
'background-color', 'border', 'border-bottom', 'border-collapse', 'border-color', 'border-style',
'border-width', 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'line-height',
'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'padding', 'padding-bottom',
'padding-left', 'padding-right', 'padding-top', 'text-align', 'text-decoration', 'vertical-align',
'white-space', 'width',
})
@dataclass
class EmlLimits:
"""EML 解析安全上限。"""
max_attachments: int = 20
max_attachment_bytes: int = 20 * 1024 * 1024
max_total_attachment_bytes: int = 50 * 1024 * 1024
max_nesting_depth: int = 3
def load_eml_limits() -> EmlLimits:
"""
从 Flask 配置读取 EML 安全上限;无应用上下文时回退默认值。
Returns:
EmlLimits: 附件数量/大小/总大小/嵌套深度上限。
"""
defaults = EmlLimits()
try:
from flask import current_app
cfg = current_app.config
except RuntimeError:
return defaults
def _int(key: str, fallback: int) -> int:
raw = cfg.get(key)
try:
value = int(raw) if raw is not None and str(raw).strip() != "" else fallback
except (TypeError, ValueError):
return fallback
return value if value > 0 else fallback
return EmlLimits(
max_attachments=_int("SHIPPING_NOTICE_EML_MAX_ATTACHMENTS", defaults.max_attachments),
max_attachment_bytes=_int(
"SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES", defaults.max_attachment_bytes
),
max_total_attachment_bytes=_int(
"SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES",
defaults.max_total_attachment_bytes,
),
max_nesting_depth=_int("SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH", defaults.max_nesting_depth),
)
def _header_str(msg: Message, name: str) -> str:
"""读取并规范化邮件头为单行字符串。"""
raw = msg.get(name)
if raw is None:
return ""
return " ".join(str(raw).split())
def _decode_part_text(part: Message | None, data: bytes) -> str:
"""
按 MIME 声明的 charset 优先解码文本字节。
核心逻辑:先试 part.get_content_charset(),再回退 utf-8/GB/latin-1,避免欧洲邮件乱码。
"""
if not data:
return ""
candidates: list[str] = []
charset = ""
if part is not None:
try:
charset = str(part.get_content_charset() or "").strip()
except Exception:
charset = ""
if charset:
candidates.append(charset)
candidates.extend(("utf-8", "utf-8-sig", "gb18030", "gbk", "latin-1", "cp1252"))
seen: set[str] = set()
for enc in candidates:
key = enc.lower().replace("_", "-")
if key in seen:
continue
seen.add(key)
try:
return data.decode(enc)
except Exception:
continue
return data.decode("utf-8", errors="replace")
def _html_to_text(raw_html: str) -> str:
"""
简易 HTML 转文本:去脚本样式、保留表格行列边界、解码实体;不执行脚本。
核心逻辑:</tr>→换行、</td>|</th>→制表符;压缩空格时不得吞掉制表符。
"""
s = re.sub(r"(?is)<(script|style).*?>.*?</\1>", "", raw_html or "")
s = re.sub(r"(?is)<br\s*/?>", "\n", s)
s = re.sub(r"(?is)</p\s*>", "\n", s)
s = re.sub(r"(?is)</h[1-6]\s*>", "\n", s)
s = re.sub(r"(?is)</tr\s*>", "\n", s)
s = re.sub(r"(?is)</(td|th)\s*>", "\t", s)
s = re.sub(r"(?is)<[^>]+>", " ", s)
s = html_lib.unescape(s)
# 只压缩空格,保留 \t 作为列分隔
s = re.sub(r" +", " ", s)
s = re.sub(r" *\t *", "\t", s)
s = re.sub(r"\n\s*\n+", "\n\n", s)
return s.strip()
def _normalize_message_id(value: str) -> str:
text = str(value or "").strip()
if not text:
return ""
return text
def _format_date(msg: Message) -> str:
raw = _header_str(msg, "Date")
if not raw:
return ""
try:
dt = parsedate_to_datetime(raw)
if dt is not None:
return dt.isoformat()
except Exception:
pass
return raw
def _looks_like_signature_or_logo(filename: str) -> bool:
name = Path(str(filename or "")).name
return bool(_SIGNATURE_LOGO_NAME_RE.search(name))
def _part_filename(part: Message, fallback: str = "attachment.bin") -> str:
name = str(part.get_filename() or "").strip()
if name:
return name
ctype = str(part.get_content_type() or "application/octet-stream")
subtype = ctype.split("/", 1)[-1] if "/" in ctype else "bin"
return f"{fallback}.{subtype}"
def _is_body_text_part(part: Message) -> bool:
"""
判定是否为邮件正文部件。
核心逻辑:text/plain|html 且非 attachment;带 filename/name 的文本部件视为附件而非正文。
"""
ctype = str(part.get_content_type() or "")
if ctype not in {"text/plain", "text/html"}:
return False
if part.get_content_disposition() == "attachment":
return False
if str(part.get_filename() or "").strip():
return False
return True
def _is_inline_or_embedded_resource(part: Message) -> bool:
"""
判定应忽略的内嵌资源 / 签名图 / Logo。
核心逻辑:仅跳过图片类 inline/CID/签名文件名;inline PDF 等可下载内容仍视为真实附件。
"""
ctype = str(part.get_content_type() or "").lower()
disp = part.get_content_disposition()
content_id = str(part.get("Content-ID") or "").strip()
filename = str(part.get_filename() or "").strip()
if not ctype.startswith("image/"):
return False
if disp == "attachment":
return False
if disp == "inline" or content_id:
return True
if filename and _looks_like_signature_or_logo(filename):
return True
return False
def _is_real_attachment(part: Message) -> bool:
"""判定是否为真实附件(排除 multipart、正文、内嵌图片、嵌套 rfc822 容器)。"""
if part.is_multipart():
return False
ctype = str(part.get_content_type() or "").lower()
if ctype == "message/rfc822":
return False
if _is_body_text_part(part):
return False
if _is_inline_or_embedded_resource(part):
return False
disp = part.get_content_disposition()
if disp == "attachment":
return True
if part.get_filename():
return True
# inline 的非图片可下载内容(如 PDF)按真实附件处理
if disp == "inline" and not ctype.startswith("image/"):
return True
if not ctype.startswith("text/") and ctype not in {"message/delivery-status", "text/calendar"}:
if disp is None and ctype.startswith("application/"):
return True
return False
def _read_part_payload(part: Message) -> bytes:
"""读取 MIME 部件解码后的原始字节;失败返回空。"""
try:
payload = part.get_payload(decode=True)
except Exception:
return b""
if isinstance(payload, bytes):
return payload
if isinstance(payload, str):
return payload.encode("utf-8", errors="ignore")
return b""
def _part_as_text(part: Message) -> str:
"""将文本部件按 charset 解码并在需要时做 HTML 清洗。"""
raw = _read_part_payload(part)
text = _decode_part_text(part, raw)
if str(part.get_content_type() or "") == "text/html":
return _html_to_text(text)
return text.strip()
def _part_as_raw_html(part: Message) -> str:
"""按 MIME charset 解码 HTML 原文,供视觉预览使用;不得经过 HTML 转文本。"""
return _decode_part_text(part, _read_part_payload(part))
def _is_attached_multipart(part: Message) -> bool:
"""
判定 multipart 是否应视为「文件附件容器」(而非可选正文结构)。
核心逻辑:Content-Disposition=attachment 或带 filename/name 的 multipart/*
(如 bundle.mime)须登记为独立附件,禁止当外层正文树展开。
"""
if not isinstance(part, Message) or not part.is_multipart():
return False
ctype = str(part.get_content_type() or "").lower()
if ctype == "message/rfc822":
return False
if part.get_content_disposition() == "attachment":
return True
if str(part.get_filename() or "").strip():
return True
try:
name_param = str(part.get_param("name") or "").strip()
except Exception:
name_param = ""
return bool(name_param)
def _iter_local_body_candidates(msg: Message, *, root: bool = True):
"""
遍历可作为「当前容器正文」的 text 部件。
核心逻辑:不穿透 message/rfc822 与附件型 multipart(二者由独立附件登记),
避免外层 body_text 吞掉附件内订单文本。
"""
ctype = str(msg.get_content_type() or "").lower()
if ctype == "message/rfc822":
return
if msg.is_multipart():
# 根若本身是附件型 multipart,正文候选应为空(由附件路径提取)
if not root and _is_attached_multipart(msg):
return
if root and _is_attached_multipart(msg):
return
parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
for part in parts:
if not isinstance(part, Message):
continue
if _is_attached_multipart(part):
continue
yield from _iter_local_body_candidates(part, root=False)
return
# 根级单部件邮件放宽到 text/*;multipart 内仅认真正无 filename 的正文部件
if root:
if _is_body_text_part(msg) or ctype in {"text/plain", "text/html"}:
yield msg
elif _is_body_text_part(msg):
yield msg
def _extract_body_text(msg: Message) -> str:
"""
提取清洗后的邮件正文(仅当前消息容器,不穿透 rfc822 / 附件型 multipart)。
核心逻辑:优先 text/plain,其次 text/html;带 filename 的部件不算正文;
转发/附件容器内订单文本只出现在独立附件行,供扁平正文单次拼接。
"""
plain = ""
html = ""
for part in _iter_local_body_candidates(msg):
ctype = str(part.get_content_type() or "")
text = _part_as_text(part)
if ctype == "text/plain" and not plain:
plain = text
elif ctype == "text/html" and not html:
html = text
return plain or html
def _extract_body_html_tables(msg: Message) -> list[str]:
"""
提取根邮件正文中的 HTML 表格并做最小白名单清洗。
核心逻辑:即使 multipart/alternative 同时存在 plain,也读取对应 HTML 的 table;
仅保留表格结构、cell 文本及 rowspan/colspan,禁止脚本、样式、链接和图片进入布局快照。
Args:
msg: 当前 EML 根消息;不穿透 rfc822 或附件型 multipart。
Returns:
最多 20 张、合计不超过 200000 字符的安全 HTML table 片段。
"""
result: list[str] = []
total_chars = 0
for part in _iter_local_body_candidates(msg):
if str(part.get_content_type() or '').lower() != 'text/html':
continue
raw = _decode_part_text(part, _read_part_payload(part))
soup = BeautifulSoup(raw or '', 'html.parser')
for table in soup.find_all('table'):
if table.find_parent('table') is not None:
continue
fragment = BeautifulSoup(str(table), 'html.parser')
for comment in fragment.find_all(string=lambda value: isinstance(value, Comment)):
comment.extract()
for tag in list(fragment.find_all(True)):
if tag.name in _HTML_DROP_TAGS:
tag.decompose()
continue
if tag.name not in _HTML_TABLE_TAGS:
tag.unwrap()
continue
allowed = {'rowspan', 'colspan'} if tag.name in {'th', 'td'} else set()
tag.attrs = {
key: value for key, value in tag.attrs.items()
if str(key).lower() in allowed
}
cleaned = str(fragment.find('table') or '').strip()
if not cleaned or total_chars + len(cleaned) > 200_000 or len(result) >= 20:
continue
result.append(cleaned)
total_chars += len(cleaned)
break
return result
def sanitize_eml_preview_html(html: str) -> str:
"""
清洗 EML 正文 HTML 为可在 sandbox iframe 中展示的有限视觉快照。
核心逻辑:仅保留邮件阅读必需的文字/表格标签与有限内联样式;图片、链接、脚本、
事件属性和定位/URL 样式全部剥离,避免邮件主动内容影响 HXOPS 页面。
Args:
html: EML 的单个 text/html 正文部件,不得传入附件或嵌套邮件正文。
Returns:
安全 HTML 片段;没有可展示内容时返回空字符串。
"""
soup = BeautifulSoup(str(html or ''), 'html.parser')
for comment in soup.find_all(string=lambda value: isinstance(value, Comment)):
comment.extract()
for tag in list(soup.find_all(True)):
name = str(tag.name or '').lower()
if name == 'style':
css = str(tag.string or '')
css = re.sub(r'(?is)@import[^;]*;', '', css)
css = re.sub(r'(?is)url\s*\([^)]*\)', '', css)
css = re.sub(r'(?is)expression\s*\([^)]*\)', '', css)
tag.string = css
continue
if name in _HTML_DROP_TAGS or name in {'form', 'input', 'button', 'textarea', 'select', 'option', 'base'}:
tag.decompose()
continue
# 邮件 CSS 由隔离 iframe 自己消费;只禁止外部资源和主动导航,不重写布局属性。
for key in list(tag.attrs):
key_name = str(key).lower()
if key_name.startswith('on') or key_name in {'action', 'formaction', 'src', 'srcset', 'href', 'xlink:href'}:
tag.attrs.pop(key, None)
if name == 'meta' and str(tag.attrs.get('http-equiv') or '').lower() == 'refresh':
tag.decompose()
continue
inline_styles = [
f'{property_name}: {value}'
for property_name, value in _parse_inline_style(str(tag.attrs.get('style') or ''))
if property_name in _EML_PREVIEW_STYLE_PROPERTIES
]
if inline_styles:
tag.attrs['style'] = '; '.join(inline_styles)
else:
tag.attrs.pop('style', None)
return str(soup).strip()
def _parse_inline_style(value: str) -> list[tuple[str, str]]:
"""解析有限 CSS 声明,拒绝 URL、表达式与控制字符等主动样式值。"""
result: list[tuple[str, str]] = []
for item in str(value or '').split(';'):
property_name, separator, raw_value = item.partition(':')
name = property_name.strip().lower()
normalized = re.sub(r'\s+', ' ', raw_value).strip()
if not separator or not name or not normalized:
continue
if any(token in normalized.lower() for token in ('url(', 'expression(', '@import', '\x00')):
continue
result.append((name, normalized[:256]))
return result
def extract_eml_preview_html(data: bytes) -> str:
"""
从原始 EML 提取根消息首个 HTML 正文并生成安全视觉快照。
Args:
data: 原始 EML 字节;禁止传入附件展开后的任意子文件。
Returns:
已清洗 HTML;邮件无 HTML 正文时返回空字符串。
"""
message = BytesParser(policy=policy.default).parsebytes(data or b'')
for part in _iter_local_body_candidates(message):
if str(part.get_content_type() or '').lower() == 'text/html':
return sanitize_eml_preview_html(_part_as_raw_html(part))
return ''
def _is_collectible_text_leaf(msg: Message) -> bool:
"""判定部件是否可作为附件容器内的可落库文本叶子(非 filename 附件)。"""
ctype = str(msg.get_content_type() or "").lower()
if ctype not in {"text/plain", "text/html"}:
return False
if not _is_body_text_part(msg) and str(msg.get_filename() or "").strip():
return False
if not _is_body_text_part(msg) and msg.get_content_disposition() == "attachment":
return False
return True
def _extract_alternative_part_text(alt: Message) -> str:
"""
从 multipart/alternative 选取单一表达:plain 优先于 html。
核心逻辑:根节点即使带 disposition=attachment 也须进入子树;
仅跳过嵌套 rfc822 / 再套一层附件型 multipart;子树内 plain 优先。
"""
plain = ""
html = ""
def _walk(msg: Message, *, is_root: bool) -> None:
nonlocal plain, html
ctype = str(msg.get_content_type() or "").lower()
if ctype == "message/rfc822":
return
# 根 alternative 本身常为附件型 multipart,不得在此处直接 return
if not is_root and _is_attached_multipart(msg):
return
if msg.is_multipart():
parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
for part in parts:
if isinstance(part, Message):
_walk(part, is_root=False)
return
if not _is_collectible_text_leaf(msg):
return
text = _part_as_text(msg).strip()
if not text:
return
if ctype == "text/plain" and not plain:
plain = text
elif ctype == "text/html" and not html:
html = text
_walk(alt, is_root=True)
return plain or html
def _extract_text_inside_attached_multipart(root: Message) -> str:
"""
从附件型 multipart 内部抽取可落库文本。
核心逻辑:
- multipart/mixed(及非 alternative 容器):独立 text/plain 与 text/html 段全部拼接保留;
- multipart/alternative(含根即为附件型 alternative):plain 优先取一份等价表达;
- 不穿透嵌套 rfc822 / 再套附件型 multipart(留给 _walk_message 按 depth 展开)。
"""
chunks: list[str] = []
def _walk(msg: Message, *, is_root: bool) -> None:
ctype = str(msg.get_content_type() or "").lower()
if ctype == "message/rfc822":
return
if not is_root and _is_attached_multipart(msg):
return
if msg.is_multipart():
if ctype == "multipart/alternative":
text = _extract_alternative_part_text(msg).strip()
if text:
chunks.append(text)
return
parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
for part in parts:
if isinstance(part, Message):
_walk(part, is_root=False)
return
if not _is_collectible_text_leaf(msg):
return
text = _part_as_text(msg).strip()
if text:
chunks.append(text)
_walk(root, is_root=True)
return "\n\n".join(chunks)
def _register_skipped_attached_multipart(
state: _ParseState,
part: Message,
*,
reason: str,
) -> None:
"""超深/超限的附件型 multipart 登记为 skipped,供完整性门禁感知。"""
state.discovered_attachment_count += 1
if reason.startswith("eml_total_attachment_size_exceeded"):
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
state.warnings.append(reason)
elif reason.startswith("eml_nesting_depth_exceeded"):
if not any(str(w).startswith("eml_nesting_depth_exceeded") for w in state.warnings):
state.warnings.append(reason)
elif reason not in state.warnings:
state.warnings.append(reason)
if len(state.attachments) >= state.limits.max_attachments:
_note_attachment_limit_exceeded(state)
return
filename = _part_filename(part, fallback="bundle")
try:
raw = part.as_bytes()
except Exception:
raw = b""
key = _next_attachment_key(state)
state.attachments.append(
{
"attachment_key": key,
"filename": filename,
"mime_type": str(part.get_content_type() or "multipart/mixed"),
"size": len(raw or b""),
"content_hash": hashlib.sha256(raw).hexdigest().lower() if raw else "",
"parse_status": "skipped",
"extracted_text": "",
"warnings": [reason],
}
)
def _register_and_expand_attached_multipart(
state: _ParseState,
part: Message,
*,
depth: int,
count_toward_total: bool,
) -> None:
"""
将 disposition=attachment / 带文件名的 multipart/* 登记为独立附件并展开内层。
核心逻辑:容器计费后子内容 count_toward_total=False;容器 extracted_text 拼接内层
全部正文段;再以 depth+1 walk 子树(嵌套容器计入深度上限)。
Args:
depth: 当前容器所在深度;展开子内容使用 depth+1。
"""
state.discovered_attachment_count += 1
if len(state.attachments) >= state.limits.max_attachments:
_note_attachment_limit_exceeded(state)
return
try:
raw = part.as_bytes()
except Exception:
raw = b""
size = len(raw or b"")
filename = _part_filename(part, fallback="bundle")
content_hash = hashlib.sha256(raw or b"").hexdigest().lower() if raw else ""
key = _next_attachment_key(state)
item: dict[str, Any] = {
"attachment_key": key,
"filename": filename,
"mime_type": str(part.get_content_type() or "multipart/mixed"),
"size": size,
"content_hash": content_hash,
"parse_status": "skipped",
"extracted_text": "",
"warnings": [],
}
_remember_payload(item, raw or b"", retain_payloads=state.retain_payloads)
if size > state.limits.max_attachment_bytes:
item["parse_status"] = "skipped"
item["warnings"].append(f"eml_attachment_too_large:{size}")
state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
state.attachments.append(item)
return
if count_toward_total:
if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
item["parse_status"] = "skipped"
item["warnings"].append("eml_total_attachment_size_exceeded")
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
state.warnings.append(
f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
)
state.attachments.append(item)
return
state.total_attachment_bytes += size
if content_hash and content_hash in state.seen_hashes:
item["parse_status"] = "duplicate"
item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
state.warnings.append(f"eml_attachment_duplicate:{filename}")
state.attachments.append(item)
return
if content_hash:
state.seen_hashes[content_hash] = key
text = _extract_text_inside_attached_multipart(part).strip()
state.attachments.append(item)
before_child_count = len(state.attachments)
# [STEP] 子内容深度 +1,与 rfc822 / 嵌套 .eml 对齐
_walk_message(part, state, depth=depth + 1, count_toward_total=False)
if text:
item["parse_status"] = "parsed"
item["extracted_text"] = text
elif len(state.attachments) > before_child_count:
# 仅含二进制子附件:容器本身无正文,仍视为成功登记
item["parse_status"] = "parsed"
item["extracted_text"] = ""
else:
item["parse_status"] = "empty"
item["warnings"].append("eml_attachment_empty_text")
def _unwrap_rfc822(part: Message) -> Message | None:
"""从 message/rfc822 部件取出内嵌 Message。"""
payload = part.get_payload()
if isinstance(payload, list) and payload:
inner = payload[0]
if isinstance(inner, Message):
return inner
if isinstance(payload, Message):
return payload
raw = _read_part_payload(part)
if not raw:
if isinstance(payload, str) and payload.strip():
raw = payload.encode("utf-8", errors="ignore")
elif isinstance(payload, bytes):
raw = payload
if not raw:
return None
try:
return BytesParser(policy=policy.default).parsebytes(raw)
except Exception:
return None
def _rfc822_container_bytes(part: Message, nested: Message | None = None) -> bytes:
"""
估算 message/rfc822 容器输入字节。
核心逻辑:优先 decode 后的 part payload;若为空(内层以 Message 对象挂载),
则用 nested.as_bytes(),以便对原生转发邮件执行单附件/总量上限。
"""
raw = _read_part_payload(part)
if raw:
return raw
target = nested
if target is None:
target = _unwrap_rfc822(part)
if target is None:
return b""
try:
return target.as_bytes()
except Exception:
return b""
def _guess_suffix(filename: str, mime_type: str) -> str:
suffix = Path(filename).suffix.lower()
if suffix:
return suffix
mime = (mime_type or "").lower()
mapping = {
"application/pdf": ".pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
"text/csv": ".csv",
"text/plain": ".txt",
"text/html": ".html",
"message/rfc822": ".eml",
"image/png": ".png",
"image/jpeg": ".jpg",
"image/webp": ".webp",
}
return mapping.get(mime, ".bin")
ExtractTextFn = Callable[[Path], tuple[str, dict[str, Any]]]
AttachmentExtractMode = Literal["deep", "preview"]
@dataclass
class _ParseState:
limits: EmlLimits
extract_text: ExtractTextFn
retain_payloads: bool = False
attachment_mode: AttachmentExtractMode = "deep"
warnings: list[str] = field(default_factory=list)
attachments: list[dict[str, Any]] = field(default_factory=list)
nested_bodies: list[str] = field(default_factory=list) # 兼容保留;v3 起 rfc822 改走 attachments,不再写入
seen_hashes: dict[str, str] = field(default_factory=dict)
total_attachment_bytes: int = 0
attachment_seq: int = 0
skipped_inline: int = 0
# 发现的真实附件总数(含因上限未登记的),用于 attachment_count
discovered_attachment_count: int = 0
def _next_attachment_key(state: _ParseState) -> str:
state.attachment_seq += 1
return f"att-{state.attachment_seq:03d}"
def _skip_inline_resource(state: _ParseState) -> None:
"""跳过内嵌资源但保留 MIME 遍历序号,保证快览与深度解析附件键一致。"""
state.skipped_inline += 1
_next_attachment_key(state)
def _remember_payload(
item: dict[str, Any],
payload: bytes,
*,
retain_payloads: bool,
) -> None:
"""仅在调用方显式要求时保留附件原始字节,避免预览链路持有大对象。"""
if retain_payloads and payload:
item["_payload_bytes"] = payload
def _is_eml_payload(*, filename: str, mime_type: str) -> bool:
"""判定附件是否为可递归的 .eml / rfc822 载荷。"""
suffix = Path(filename or "").suffix.lower()
mime = (mime_type or "").lower()
return suffix == ".eml" or mime in {"message/rfc822", "application/eml"}
_PREVIEW_READY_SUFFIXES = frozenset(
{
".pdf",
".doc",
".docx",
".xls",
".xlsx",
".csv",
".txt",
".html",
".htm",
".xml",
".json",
".eml",
".msg",
".png",
".jpg",
".jpeg",
".webp",
".bmp",
".tif",
".tiff",
}
)
_PREVIEW_ARCHIVE_SUFFIXES = frozenset(
{".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz"}
)
_PREVIEW_EXECUTABLE_SUFFIXES = frozenset(
{".exe", ".dll", ".bat", ".cmd", ".com", ".msi", ".vbs", ".js", ".jar", ".ps1", ".scr"}
)
_PREVIEW_MACRO_SUFFIXES = frozenset({".docm", ".xlsm", ".pptm", ".xlam", ".xltm"})
_PREVIEW_READY_MIME_PREFIXES = ("text/", "image/")
_PREVIEW_READY_MIMES = frozenset(
{
"application/pdf",
"message/rfc822",
"application/eml",
"application/msword",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}
)
_PREVIEW_ARCHIVE_MIMES = frozenset(
{
"application/zip",
"application/x-zip-compressed",
"application/x-7z-compressed",
"application/x-rar-compressed",
"application/gzip",
"application/x-tar",
}
)
_PREVIEW_EXECUTABLE_MIMES = frozenset(
{
"application/x-msdownload",
"application/x-msdos-program",
"application/x-sh",
"application/x-powershell",
"application/java-archive",
}
)
def _preview_catalog_reason(
*,
filename: str,
mime_type: str,
is_inline_resource: bool,
) -> tuple[bool, str]:
"""
根据目录阶段可见事实判断附件是否可进入后续深度解析。
Returns:
tuple[bool, str]: (是否可进入深度解析, 原因码)。
"""
suffix = Path(str(filename or "")).suffix.lower()
mime = str(mime_type or "").lower()
if is_inline_resource:
if _looks_like_signature_or_logo(filename):
return False, "signature_or_logo"
return False, "inline_resource"
if suffix in _PREVIEW_ARCHIVE_SUFFIXES or mime in _PREVIEW_ARCHIVE_MIMES:
return False, "archive"
if suffix in _PREVIEW_MACRO_SUFFIXES or "macroenabled" in mime:
return False, "macro_enabled"
if suffix in _PREVIEW_EXECUTABLE_SUFFIXES or mime in _PREVIEW_EXECUTABLE_MIMES:
return False, "executable"
if suffix in _PREVIEW_READY_SUFFIXES:
return True, "ready_for_extraction"
if mime in _PREVIEW_READY_MIMES or any(mime.startswith(prefix) for prefix in _PREVIEW_READY_MIME_PREFIXES):
return True, "ready_for_extraction"
return False, "unknown_binary"
def _expand_eml_file_attachment(
*,
state: _ParseState,
payload: bytes,
depth: int,
) -> tuple[str, str, list[str]]:
"""
在共享 _ParseState 下展开 .eml 文件附件。
核心逻辑:深度 +1 后复用同一 attachments/限额/哈希,避免重新 parse_eml_bytes(depth=0)
绕过嵌套与附件总数限制;容器项自身只保留内层主题+正文。
容器字节已在登记时计入 total_attachment_bytes,子内容 count_toward_total=False
避免与容器双重计费,同时封死「多个近似空壳大 EML」绕过总量上限。
Returns:
(parse_status, extracted_text, warnings)
"""
next_depth = depth + 1
if next_depth > state.limits.max_nesting_depth:
warn = f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}"
if warn not in state.warnings:
state.warnings.append(warn)
return "skipped", "", [warn]
try:
nested = BytesParser(policy=policy.default).parsebytes(payload or b"")
except Exception as exc:
return "failed", "", [f"eml_attachment_extract_failed:{exc}"]
subject = _header_str(nested, "Subject")
body = _extract_body_text(nested)
chunks: list[str] = []
if subject:
chunks.append(f"Subject: {subject}")
if body:
chunks.append(body)
# 子附件计入同一 state;大小已由容器计费,不再对子 payload 累加总字节
_walk_message(nested, state, depth=next_depth, count_toward_total=False)
text = "\n\n".join(chunks).strip()
if not text:
return "empty", "", ["eml_attachment_empty_text"]
return "parsed", text, []
def _extract_attachment_text(
*,
state: _ParseState,
filename: str,
mime_type: str,
payload: bytes,
depth: int,
) -> tuple[str, str, list[str]]:
"""
抽取单个附件文本。
核心逻辑:.eml 走共享状态展开;其他类型写临时文件调用 extract_text(PDF/DOCX 等)。
Returns:
(parse_status, extracted_text, warnings)
"""
if _is_eml_payload(filename=filename, mime_type=mime_type):
return _expand_eml_file_attachment(state=state, payload=payload or b"", depth=depth)
suffix = _guess_suffix(filename, mime_type)
tmp_path: Path | None = None
try:
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
tmp.write(payload)
tmp_path = Path(tmp.name)
text, meta = state.extract_text(tmp_path)
warn = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
if not str(text or "").strip():
return "empty", "", warn or ["eml_attachment_empty_text"]
return "parsed", str(text).strip(), warn
except Exception as exc:
return "failed", "", [f"eml_attachment_extract_failed:{exc}"]
finally:
if tmp_path is not None:
try:
tmp_path.unlink(missing_ok=True)
except OSError:
pass
def _note_attachment_limit_exceeded(state: _ParseState) -> None:
"""刷新「附件数量超限」警告,带上当前 discovered 总数。"""
prefix = "eml_attachment_limit_exceeded:"
state.warnings = [w for w in state.warnings if not str(w).startswith(prefix)]
state.warnings.append(
f"{prefix}{state.limits.max_attachments}:discovered={state.discovered_attachment_count}"
)
def _append_attachment(
state: _ParseState,
*,
filename: str,
mime_type: str,
payload: bytes,
depth: int,
count_toward_total: bool = True,
) -> None:
"""
在安全上限内登记并抽取单个真实附件。
Args:
count_toward_total: True 时把本附件 payload 计入总大小配额。
由 .eml 容器展开出的子附件传 False(容器已计费,避免双重计费)。
"""
state.discovered_attachment_count += 1
# [STEP 1] 数量上限:仍计入 discovered,但不登记抽正文
if len(state.attachments) >= state.limits.max_attachments:
_note_attachment_limit_exceeded(state)
return
size = len(payload or b"")
content_hash = hashlib.sha256(payload or b"").hexdigest().lower()
key = _next_attachment_key(state)
item: dict[str, Any] = {
"attachment_key": key,
"filename": filename,
"mime_type": mime_type or "application/octet-stream",
"size": size,
"content_hash": content_hash,
"parse_status": "skipped",
"extracted_text": "",
"warnings": [],
}
# 仅在显式深度链路保留原始字节;预览模式不再为后续派生资产持有 payload。
_remember_payload(item, payload or b"", retain_payloads=state.retain_payloads)
# [STEP 2] 单附件 / 总大小上限
# 计费规则:顶层真实附件(含 .eml 容器)计入总量;从已计费 .eml 展开的子内容不计。
if size > state.limits.max_attachment_bytes:
item["parse_status"] = "skipped"
item["warnings"].append(f"eml_attachment_too_large:{size}")
state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
state.attachments.append(item)
return
if count_toward_total:
if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
item["parse_status"] = "skipped"
item["warnings"].append("eml_total_attachment_size_exceeded")
if not any(
str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings
):
state.warnings.append(
f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
)
state.attachments.append(item)
return
state.total_attachment_bytes += size
# [STEP 3] 同信内内容哈希去重(含嵌套 .eml 展开后的子附件)
if content_hash in state.seen_hashes:
item["parse_status"] = "duplicate"
item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
state.warnings.append(f"eml_attachment_duplicate:{filename}")
state.attachments.append(item)
return
state.seen_hashes[content_hash] = key
# [STEP 4] 先占位登记,再抽取/展开,确保 .eml 递归子附件计入同一数量上限
state.attachments.append(item)
status, text, warn = _extract_attachment_text(
state=state,
filename=filename,
mime_type=mime_type,
payload=payload or b"",
depth=depth,
)
item["parse_status"] = status
item["extracted_text"] = text
item["warnings"].extend(warn)
if status == "failed":
state.warnings.append(f"eml_attachment_extract_failed:{filename}")
def _register_and_expand_rfc822(
state: _ParseState,
part: Message,
nested: Message,
*,
depth: int,
) -> None:
"""
将原生 message/rfc822 登记为独立附件,并展开内层正文附件。
核心逻辑:与 .eml 文件附件对齐——容器行保存主题+正文;子附件 count_toward_total=False;
不写入 nested_bodies,避免与 attachment.extracted_text / 扁平正文双重拼接。
Args:
state: 共享解析状态(容器字节须已由调用方计费或无需计费)。
part: 外层 message/rfc822 MIME 部件。
nested: 已 unwrap 的内层 Message。
depth: 当前外层深度;内层 walk 使用 depth+1。
"""
state.discovered_attachment_count += 1
if len(state.attachments) >= state.limits.max_attachments:
_note_attachment_limit_exceeded(state)
return
raw = _rfc822_container_bytes(part, nested)
filename = str(part.get_filename() or "").strip() or "forwarded-message.eml"
content_hash = hashlib.sha256(raw).hexdigest().lower() if raw else ""
key = _next_attachment_key(state)
item: dict[str, Any] = {
"attachment_key": key,
"filename": filename,
"mime_type": "message/rfc822",
"size": len(raw),
"content_hash": content_hash,
"parse_status": "empty",
"extracted_text": "",
"warnings": [],
}
_remember_payload(item, raw or b"", retain_payloads=state.retain_payloads)
if content_hash and content_hash in state.seen_hashes:
item["parse_status"] = "duplicate"
item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
state.warnings.append(f"eml_attachment_duplicate:{filename}")
state.attachments.append(item)
return
if content_hash:
state.seen_hashes[content_hash] = key
subject = _header_str(nested, "Subject")
body = _extract_body_text(nested)
chunks: list[str] = []
if subject:
chunks.append(f"Subject: {subject}")
if body:
chunks.append(body)
text = "\n\n".join(chunks).strip()
state.attachments.append(item)
# [STEP] 先占位再展开,使内层子附件与容器共享数量上限
_walk_message(nested, state, depth=depth + 1, count_toward_total=False)
if text:
item["parse_status"] = "parsed"
item["extracted_text"] = text
else:
item["parse_status"] = "empty"
item["warnings"].append("eml_attachment_empty_text")
def _register_skipped_nested_rfc822(state: _ParseState, part: Message, *, reason: str) -> None:
"""
超深/不可读/超限的 message/rfc822 登记为 skipped 附件行,供前端徽标感知「不完整」。
Args:
state: 共享解析状态。
part: 被跳过的 rfc822 部件。
reason: 警告码(如 eml_nesting_depth_exceeded:N / eml_attachment_too_large:N)。
"""
state.discovered_attachment_count += 1
# [STEP] 总量超限只保留一条顶层 warning;其它 reason 按原文去重
if reason.startswith("eml_total_attachment_size_exceeded"):
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
state.warnings.append(reason)
elif reason not in state.warnings:
state.warnings.append(reason)
if len(state.attachments) >= state.limits.max_attachments:
_note_attachment_limit_exceeded(state)
return
filename = str(part.get_filename() or "").strip() or "forwarded-message.eml"
raw = _rfc822_container_bytes(part)
key = _next_attachment_key(state)
state.attachments.append(
{
"attachment_key": key,
"filename": filename,
"mime_type": "message/rfc822",
"size": len(raw),
"content_hash": hashlib.sha256(raw).hexdigest().lower() if raw else "",
"parse_status": "skipped",
"extracted_text": "",
"warnings": [reason],
}
)
def _maybe_charge_rfc822_container(
state: _ParseState,
part: Message,
nested: Message,
*,
count_toward_total: bool,
) -> bool:
"""
对原生 message/rfc822 转发容器执行单附件/总量上限并计费。
核心逻辑:与 .eml 文件附件一致——容器字节计入配额后,内层展开 count_toward_total=False。
Returns:
True 表示可通过并已计费(或无需计费);False 表示已登记 skipped,调用方勿再展开。
"""
if not count_toward_total:
return True
raw = _rfc822_container_bytes(part, nested)
size = len(raw)
filename = str(part.get_filename() or "").strip() or "forwarded-message.eml"
if size > state.limits.max_attachment_bytes:
reason = f"eml_attachment_too_large:{size}"
state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
_register_skipped_nested_rfc822(state, part, reason=reason)
return False
if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
reason = f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
_register_skipped_nested_rfc822(state, part, reason=reason)
return False
state.total_attachment_bytes += size
return True
def _append_preview_attachment(
state: _ParseState,
*,
filename: str,
mime_type: str,
payload: bytes,
count_toward_total: bool = True,
is_inline_resource: bool = False,
forced_status: str | None = None,
forced_warning: str | None = None,
) -> None:
"""
仅登记附件目录,不做正文抽取或递归展开。
核心逻辑:目录阶段只保留文件名、MIME、大小、哈希、内嵌标记和后续是否允许深度解析。
forced_status/forced_warning 用于记录超深、不可读嵌套等目录不完整事实。
"""
state.discovered_attachment_count += 1
if len(state.attachments) >= state.limits.max_attachments:
_note_attachment_limit_exceeded(state)
return
raw = payload or b""
size = len(raw)
content_hash = hashlib.sha256(raw).hexdigest().lower() if raw else ""
ready_for_extraction, catalog_reason = _preview_catalog_reason(
filename=filename,
mime_type=mime_type,
is_inline_resource=is_inline_resource,
)
key = _next_attachment_key(state)
item: dict[str, Any] = {
"attachment_key": key,
"filename": filename,
"mime_type": mime_type or "application/octet-stream",
"size": size,
"content_hash": content_hash,
"parse_status": "ready_for_extraction" if ready_for_extraction else "directory_only",
"extracted_text": "",
"warnings": [],
"ready_for_extraction": ready_for_extraction,
"is_inline_resource": is_inline_resource,
"catalog_reason": catalog_reason,
}
_remember_payload(item, raw, retain_payloads=state.retain_payloads)
if forced_warning:
item["parse_status"] = forced_status or "skipped"
item["ready_for_extraction"] = False
item["warnings"].append(forced_warning)
if forced_warning.startswith("eml_total_attachment_size_exceeded"):
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
state.warnings.append(forced_warning)
elif forced_warning not in state.warnings:
state.warnings.append(forced_warning)
state.attachments.append(item)
return
if size > state.limits.max_attachment_bytes:
item["parse_status"] = "skipped"
item["ready_for_extraction"] = False
item["warnings"].append(f"eml_attachment_too_large:{size}")
state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
state.attachments.append(item)
return
if count_toward_total:
if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
item["parse_status"] = "skipped"
item["ready_for_extraction"] = False
item["warnings"].append("eml_total_attachment_size_exceeded")
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
state.warnings.append(
f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
)
state.attachments.append(item)
return
state.total_attachment_bytes += size
if content_hash and content_hash in state.seen_hashes:
item["parse_status"] = "duplicate"
item["ready_for_extraction"] = False
item["catalog_reason"] = "duplicate"
item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
state.warnings.append(f"eml_attachment_duplicate:{filename}")
state.attachments.append(item)
return
if content_hash:
state.seen_hashes[content_hash] = key
state.attachments.append(item)
def _walk_message_preview(
msg: Message,
state: _ParseState,
*,
depth: int,
count_toward_total: bool = True,
) -> None:
"""
遍历 MIME 树并仅登记附件目录。
核心逻辑:正文提取仍由根消息自身负责;目录阶段对 message/rfc822 和附件型 multipart
只登记容器,不递归进入其内部附件,确保上传时延与附件正文/OCR/表格无关。
"""
if depth > state.limits.max_nesting_depth:
state.warnings.append(f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}")
return
if not msg.is_multipart():
is_inline = _is_inline_or_embedded_resource(msg)
if is_inline:
_skip_inline_resource(state)
elif _is_real_attachment(msg):
_append_preview_attachment(
state,
filename=_part_filename(msg),
mime_type=str(msg.get_content_type() or "application/octet-stream"),
payload=_read_part_payload(msg),
count_toward_total=count_toward_total,
)
return
parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
for part in parts:
if not isinstance(part, Message):
continue
ctype = str(part.get_content_type() or "").lower()
if ctype == "message/rfc822":
_append_preview_attachment(
state,
filename=str(part.get_filename() or "").strip() or "forwarded-message.eml",
mime_type="message/rfc822",
payload=_rfc822_container_bytes(part),
count_toward_total=count_toward_total,
forced_status="skipped" if _unwrap_rfc822(part) is None else None,
forced_warning="eml_nested_message_unreadable" if _unwrap_rfc822(part) is None else None,
)
continue
if part.is_multipart():
if _is_attached_multipart(part):
try:
raw = part.as_bytes()
except Exception:
raw = b""
_append_preview_attachment(
state,
filename=_part_filename(part, fallback="bundle"),
mime_type=str(part.get_content_type() or "multipart/mixed"),
payload=raw,
count_toward_total=count_toward_total,
)
continue
_walk_message_preview(
part,
state,
depth=depth,
count_toward_total=count_toward_total,
)
continue
is_inline = _is_inline_or_embedded_resource(part)
if is_inline:
# 内嵌签名图不是用户可识别的业务附件,不能占用附件数量或预算。
_skip_inline_resource(state)
continue
if _is_body_text_part(part):
continue
if _is_real_attachment(part):
_append_preview_attachment(
state,
filename=_part_filename(part),
mime_type=str(part.get_content_type() or "application/octet-stream"),
payload=_read_part_payload(part),
count_toward_total=count_toward_total,
)
def _walk_message(
msg: Message,
state: _ParseState,
*,
depth: int,
count_toward_total: bool = True,
) -> None:
"""
递归遍历 MIME 树:收集真实附件,展开 message/rfc822(含内层正文),跳过内嵌图片。
Args:
msg: 当前邮件 Message。
state: 共享解析状态。
depth: 当前嵌套深度(顶层为 0)。
count_toward_total: 本层登记的附件是否计入总大小配额。
"""
if depth > state.limits.max_nesting_depth:
state.warnings.append(f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}")
return
if not msg.is_multipart():
if _is_real_attachment(msg):
_append_attachment(
state,
filename=_part_filename(msg),
mime_type=str(msg.get_content_type() or "application/octet-stream"),
payload=_read_part_payload(msg),
depth=depth,
count_toward_total=count_toward_total,
)
return
parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
for part in parts:
if not isinstance(part, Message):
continue
ctype = str(part.get_content_type() or "").lower()
if ctype == "message/rfc822":
if depth + 1 > state.limits.max_nesting_depth:
_register_skipped_nested_rfc822(
state,
part,
reason=f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}",
)
continue
nested = _unwrap_rfc822(part)
if nested is None:
_register_skipped_nested_rfc822(
state,
part,
reason="eml_nested_message_unreadable",
)
continue
# [STEP] 原生转发容器须计费,防止绕过单附件/总量上限
if not _maybe_charge_rfc822_container(
state,
part,
nested,
count_toward_total=count_toward_total,
):
continue
# 成功路径登记为独立附件(与 .eml 文件附件一致),再展开内层
_register_and_expand_rfc822(state, part, nested, depth=depth)
continue
if part.is_multipart():
# 附件型 multipart(filename / disposition=attachment)须独立登记,禁止当正文树展开
if _is_attached_multipart(part):
next_depth = depth + 1
if next_depth > state.limits.max_nesting_depth:
_register_skipped_attached_multipart(
state,
part,
reason=f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}",
)
continue
_register_and_expand_attached_multipart(
state,
part,
depth=depth,
count_toward_total=count_toward_total,
)
continue
_walk_message(
part,
state,
depth=depth,
count_toward_total=count_toward_total,
)
continue
if _is_inline_or_embedded_resource(part):
_skip_inline_resource(state)
continue
if _is_body_text_part(part):
continue
if _is_real_attachment(part):
_append_attachment(
state,
filename=_part_filename(part),
mime_type=str(part.get_content_type() or "application/octet-stream"),
payload=_read_part_payload(part),
depth=depth,
count_toward_total=count_toward_total,
)
def _compose_flat_text(
*,
subject: str,
body_text: str,
attachments: list[dict[str, Any]],
) -> str:
"""将主题、正文(含转发段)与各附件文本拼成下游订单解析用的扁平正文。"""
parts: list[str] = []
if subject:
parts.append(f"Subject: {subject}")
if body_text:
parts.append(body_text)
for item in attachments:
if item.get("parse_status") != "parsed":
continue
text = str(item.get("extracted_text") or "").strip()
if not text:
continue
name = str(item.get("filename") or item.get("attachment_key") or "attachment")
parts.append(f"--- attachment: {name} ---\n{text}")
return "\n\n".join(parts)
def parse_eml_bytes(
data: bytes,
*,
extract_text: ExtractTextFn,
limits: EmlLimits | None = None,
depth: int = 0,
retain_payloads: bool = False,
attachment_mode: AttachmentExtractMode = "deep",
) -> tuple[str, dict[str, Any]]:
"""
结构化解析 EML 字节流。
核心逻辑:提取邮件头与清洗正文;`deep` 模式递归抽取附件全文,
`preview` 模式仅登记附件目录(名称、MIME、大小、哈希、是否内嵌、是否允许后续深度解析)。
Args:
data: .eml 原始字节。
extract_text: 叶附件文本抽取函数,签名与 extract_notice_text 一致。
limits: 安全上限;为空时从配置/默认加载。
depth: 当前嵌套深度(供嵌套 .eml 附件复用)。
retain_payloads: True 时在 attachments[*]._payload_bytes 保留二进制供派生资产;
默认 False,返回前剥离,避免测试/JSON 路径泄漏。
attachment_mode: `deep` 递归抽附件文本;`preview` 只生成附件目录。
Returns:
tuple[str, dict]: (扁平拼接文本, meta含 email/attachments/attachment_count/warnings)。
"""
limits = limits or load_eml_limits()
if depth > limits.max_nesting_depth:
return "", {
"file_type": "eml",
"warnings": [f"eml_nesting_depth_exceeded:{limits.max_nesting_depth}"],
"email": {},
"attachments": [],
"attachment_count": 0,
"attachment_registered_count": 0,
}
msg = BytesParser(policy=policy.default).parsebytes(data or b"")
subject = _header_str(msg, "Subject")
from_addr = _header_str(msg, "From")
to_addr = _header_str(msg, "To")
date_val = _format_date(msg)
message_id = _normalize_message_id(_header_str(msg, "Message-ID") or _header_str(msg, "Message-Id"))
body_text = _extract_body_text(msg)
body_html_tables = _extract_body_html_tables(msg)
state = _ParseState(
limits=limits,
extract_text=extract_text,
retain_payloads=retain_payloads,
attachment_mode=attachment_mode,
)
if attachment_mode == "preview":
_walk_message_preview(msg, state, depth=depth)
else:
_walk_message(msg, state, depth=depth)
if state.skipped_inline:
state.warnings.append(f"eml_inline_resources_skipped:{state.skipped_inline}")
body_segments = [body_text, *state.nested_bodies]
combined_body = "\n\n".join(segment for segment in body_segments if segment)
email_meta = {
"message_id": message_id,
"subject": subject,
"from": from_addr,
"to": to_addr,
"date": date_val,
"body_text": combined_body,
"body_html_tables": body_html_tables,
}
flat = _compose_flat_text(
subject=subject,
body_text=combined_body,
attachments=state.attachments if attachment_mode == "deep" else [],
)
meta: dict[str, Any] = {
"file_type": "eml",
"eml_attachment_mode": attachment_mode,
"warnings": list(state.warnings),
"email": email_meta,
"attachments": list(state.attachments),
# attachment_count = 发现的真实附件总数(含因上限未登记的)
"attachment_count": int(state.discovered_attachment_count),
"attachment_registered_count": len(state.attachments),
}
# 注意:attachments[*]._payload_bytes 仅供同进程持久化派生资产,不得序列化进 DB/API
if not retain_payloads:
strip_attachment_payloads(meta)
return flat, meta
def pop_attachment_payload(item: dict[str, Any]) -> bytes:
"""
取出并移除附件上的内存 payload。
Args:
item: parse_eml_bytes 产出的单条 attachment 摘要。
Returns:
原始字节;无则 b""。
"""
if not isinstance(item, dict):
return b""
raw = item.pop("_payload_bytes", None)
return raw if isinstance(raw, (bytes, bytearray)) else b""
def strip_attachment_payloads(meta: dict[str, Any] | None) -> dict[str, Any]:
"""
就地剥除 meta.attachments 中的 `_payload_bytes`,防止二进制泄漏到摘要/API。
Returns:
同一 meta 引用(或空 dict)。
"""
if not isinstance(meta, dict):
return {}
for item in meta.get("attachments") or []:
if isinstance(item, dict):
item.pop("_payload_bytes", None)
return meta