蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线模拟 CDO.Message 纯文本/HTML/MHTML/附件组装、远程 SMTP 配置与 CRLF 注入拦截

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-send-email.py
explore-send-email.py189 行
"""Offline Classic ASP / VBScript verifier for Chapter 13 (send-email)."""
from __future__ import annotations

import json
import re
from email.message import EmailMessage

VERSION = "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)"

CDO_SENDUSING = "http://schemas.microsoft.com/cdo/configuration/sendusing"
CDO_SMTPSERVER = "http://schemas.microsoft.com/cdo/configuration/smtpserver"
CDO_SMTPPORT = "http://schemas.microsoft.com/cdo/configuration/smtpserverport"


class CdoMessageSim:
    """Offline simulation of Classic ASP CDO.Message (CDOSYS) without network SMTP."""

    def __init__(self) -> None:
        self.subject = ""
        self.sender = ""
        self.to = ""
        self.cc = ""
        self.bcc = ""
        self.text_body = ""
        self.html_body = ""
        self.mhtml_source = ""
        self.attachments: list[str] = []
        self.config_fields: dict[str, object] = {}
        self.config_updated = False

    def create_mhtml_body(self, uri: str) -> str:
        if not (uri.startswith("http://") or uri.startswith("https://") or uri.startswith("file://")):
            raise ValueError(f"Unsupported MHTML URI: {uri}")
        self.mhtml_source = uri
        return "multipart/related"

    def add_attachment(self, path: str) -> bool:
        if not re.match(r"^[A-Za-z]:\\.+", path):
            return False
        self.attachments.append(path)
        return True

    def build_envelope(self) -> dict[str, object]:
        for field_val in (self.subject, self.sender, self.to, self.cc, self.bcc):
            if "\r" in field_val or "\n" in field_val:
                raise ValueError("Header injection CRLF detected")
        msg = EmailMessage()
        msg["Subject"] = self.subject
        msg["From"] = self.sender
        msg["To"] = self.to
        if self.cc:
            msg["Cc"] = self.cc
        if self.html_body:
            msg.set_content(self.html_body, subtype="html")
        else:
            msg.set_content(self.text_body)
        for att in self.attachments:
            filename = att.rsplit("\\", 1)[-1]
            msg.add_attachment(b"sample-attachment", maintype="text", subtype="plain", filename=filename)
        recipients = [a for a in (self.to, self.cc, self.bcc) if a]
        return {
            "content_type": msg.get_content_type(),
            "has_bcc_header": "Bcc" in msg,
            "envelope_recipients": recipients,
            "has_cc_header": "Cc" in msg,
            "attachment_names": [p.get_filename() for p in msg.iter_attachments()],
        }


def main() -> None:
    m1 = CdoMessageSim()
    m1.subject = "Sending email with CDO"
    m1.sender = "mymail@mydomain.com"
    m1.to = "someone@somedomain.com"
    m1.cc = "someoneelse2@somedomain.com"
    m1.bcc = "someoneelse@somedomain.com"
    m1.text_body = "This is a message."
    env1 = m1.build_envelope()

    m2 = CdoMessageSim()
    m2.subject = "Sending email with CDO"
    m2.sender = "mymail@mydomain.com"
    m2.to = "someone@somedomain.com"
    m2.html_body = "<h1>This is a message.</h1>"
    env2 = m2.build_envelope()
    mhtml_http = m2.create_mhtml_body("http://example.local/asp/")
    mhtml_file = m2.create_mhtml_body("file://c:/mydocuments/test.htm")

    m3 = CdoMessageSim()
    m3.subject = "Sending email with CDO"
    m3.sender = "mymail@mydomain.com"
    m3.to = "someone@somedomain.com"
    m3.text_body = "This is a message."
    bad_att_ok = m3.add_attachment("c:mydocumentstest.txt")
    good_att_ok = m3.add_attachment(r"c:\mydocuments\test.txt")
    env3 = m3.build_envelope()

    m4 = CdoMessageSim()
    m4.config_fields[CDO_SENDUSING] = 2
    m4.config_fields[CDO_SMTPSERVER] = "smtp.server.com"
    m4.config_fields[CDO_SMTPPORT] = 25
    m4.config_updated = True
    m4.subject = "Bad\r\nBcc: evil@example.com"
    m4.sender = "mymail@mydomain.com"
    m4.to = "someone@somedomain.com"
    crlf_blocked = False
    try:
        m4.build_envelope()
    except ValueError:
        crlf_blocked = True

    cases = [
        {
            "name": "cdo_plain_text_and_cc_bcc",
            "summary": "核对 CDO.Message 纯文本发信及 Cc/Bcc 头部策略(Bcc 仅进入投递信封不暴露于 MIME 头)",
            "expected": {
                "content_type": "text/plain",
                "has_cc_header": True,
                "has_bcc_header": False,
                "recipient_count": 3,
            },
            "actual": {
                "content_type": env1["content_type"],
                "has_cc_header": env1["has_cc_header"],
                "has_bcc_header": env1["has_bcc_header"],
                "recipient_count": len(env1["envelope_recipients"]),
            },
            "passed": True,
        },
        {
            "name": "cdo_html_and_mhtml_body",
            "summary": "验证 HTMLBody 的 text/html 类型及 CreateMHTMLBody 对 http:// 与 file:// URI 的离线校验",
            "expected": {
                "html_content_type": "text/html",
                "mhtml_http_type": "multipart/related",
                "mhtml_file_type": "multipart/related",
            },
            "actual": {
                "html_content_type": env2["content_type"],
                "mhtml_http_type": mhtml_http,
                "mhtml_file_type": mhtml_file,
            },
            "passed": True,
        },
        {
            "name": "cdo_attachment_path_validation",
            "summary": "校验 AddAttachment 路径分隔符(拦截缺失反斜杠路径并封装合法附件)",
            "expected": {
                "missing_backslash_accepted": False,
                "valid_path_accepted": True,
                "content_type": "multipart/mixed",
                "attachment_names": ["test.txt"],
            },
            "actual": {
                "missing_backslash_accepted": bad_att_ok,
                "valid_path_accepted": good_att_ok,
                "content_type": env3["content_type"],
                "attachment_names": env3["attachment_names"],
            },
            "passed": True,
        },
        {
            "name": "cdo_remote_smtp_configuration",
            "summary": "核对远程 SMTP 的 Configuration.Fields 三个架构 URI、Fields.Update 与 CRLF 注入拦截",
            "expected": {
                "sendusing": 2,
                "smtpserver": "smtp.server.com",
                "smtpport": 25,
                "updated": True,
                "crlf_blocked": True,
            },
            "actual": {
                "sendusing": m4.config_fields[CDO_SENDUSING],
                "smtpserver": m4.config_fields[CDO_SMTPSERVER],
                "smtpport": m4.config_fields[CDO_SMTPPORT],
                "updated": m4.config_updated,
                "crlf_blocked": crlf_blocked,
            },
            "passed": True,
        },
    ]
    for c in cases:
        c["passed"] = c["actual"] == c["expected"]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/asp-send-email-lab/explore-send-email.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-send-email.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:ASP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1450.zip

下载课程关联工程包:ASP

课程关联工程包(登记关联36章) · 含当前章节或实例 · mbskycom202612a1425.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习