# Reads the message packages/integration/email prints and checks it with Python's own `email` parser: an independent reader # of what `toMime` writes. Usage: python3 check_mime.py import email import email.policy import sys raw = open(sys.argv[1], "rb").read() assert b"\r\n" in raw and b"\n" not in raw.replace(b"\r\n", b""), "every line ends in CRLF" assert all(b < 128 for b in raw), "the message is ASCII" for line in raw.split(b"\r\n"): assert len(line) <= 998, "no line is over RFC 5322's limit" msg = email.message_from_bytes(raw, policy=email.policy.default) defects = list(msg.defects) + [d for part in msg.walk() for d in part.defects] assert not defects, f"the parser found defects: {defects}" assert msg["Subject"] == "Vaša vstopnica za dogodek: čudovit večer na gradu, ki se ga boste še dolgo spominjali", msg["Subject"] assert msg["From"].addresses[0].display_name == 'Žiga "Vidni" Novak', msg["From"] assert msg["From"].addresses[0].addr_spec == "info@example.com" to = msg["To"].addresses assert [a.addr_spec for a in to] == ["ana@example.com", "bor@example.com"], msg["To"] assert to[1].display_name == "Bor Šuštar", to[1].display_name assert msg["Cc"].addresses[0].addr_spec == "cene@example.com" assert msg["Bcc"] is None and b"skrito@example.com" not in raw, "bcc isn't written" assert msg["Reply-To"].addresses[0].addr_spec == "lastnik@example.com" assert msg["List-Unsubscribe"] == "" assert msg["X-Oznaka"] == "račun", msg["X-Oznaka"] assert msg["MIME-Version"] == "1.0" assert msg["Message-ID"].endswith("@example.com>") assert msg.get_content_type() == "multipart/mixed", msg.get_content_type() long = "Pozdravljeni, to je dolgo sporočilo s črkami č, š in ž, ki sega čez mejo šestinsedemdesetih znakov v vrstici. = in pika.\n.vrstica s piko\nKonec " plain = msg.get_body(preferencelist=("plain",)).get_content() assert plain.replace("\r\n", "\n").rstrip("\n") == long, repr(plain) html = msg.get_body(preferencelist=("html",)).get_content() assert html.replace("\r\n", "\n").rstrip("\n") == f'

{long}

', repr(html) files = {part.get_filename(): part for part in msg.iter_attachments()} assert set(files) == {"račun št. 5.pdf", "dogodek.ics"}, set(files) assert files["račun št. 5.pdf"].get_content() == bytes(range(256)) assert files["račun št. 5.pdf"].get_content_type() == "application/pdf" assert files["dogodek.ics"].get_content_type() == "text/calendar" inline = [p for p in msg.walk() if p.get("Content-ID")] assert len(inline) == 1 and inline[0]["Content-ID"] == "" and inline[0].get_content_disposition() == "inline" assert inline[0].get_payload(decode=True) == bytes([137, 80, 78, 71]) kinds = [p.get_content_type() for p in msg.walk()] assert kinds[:4] == ["multipart/mixed", "multipart/related", "multipart/alternative", "text/plain"], kinds print("Python's email parser reads the message back exactly")