PythonIntermediate · Windows, macOS, or Linux with Python 3.12+

Create a quoted local reply draft

Create an unsent reply EML with a quoted plain-text excerpt and threading headers.

Before you begin

  • Python 3.12 or newer
What this script changesReads local exports and creates a separate result, refusing overwrite. EML files are capped at 25 MiB; MBOX exports at 100 MiB and 5000 messages. Output can contain private message text and addresses. Drafts are local .eml files and are never sent. Attachment files are copied as data and never executed.

Set up your example

  1. Save the complete code as eml-reply-draft.py in a working folder.
  2. Save the provided sample files in that same folder; run commands from that folder.

Sample files in this download:

  • sample.eml
  • sample.mbox
  • body.txt
  • note.txt

Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is eml-reply-draft.py.

Run the script

Run command
python "eml-reply-draft.py" --input "sample.eml" --from-address "bo@example.test" --output "reply.eml"

If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.

What to expect

Create an unsent reply EML with a quoted plain-text excerpt and threading headers. The fixture draft is from Bo to Ada and starts with Thanks for the update.

The complete script

eml-reply-draft.py
#!/usr/bin/env python3
'Create a quoted local reply draft'
import argparse
import json
from pathlib import Path

def write_json(path, value):
    data = json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    with Path(path).open("x", encoding="utf-8", newline="") as handle:
        handle.write(data)

import re
import hashlib
import mimetypes
import mailbox
from collections import Counter, defaultdict
from datetime import datetime, timezone
from email import policy
from email.parser import BytesParser
from email.message import EmailMessage
from email.utils import getaddresses, parseaddr, formataddr, parsedate_to_datetime, format_datetime, make_msgid

def raw(path,limit=25*1024*1024):
    if Path(path).stat().st_size>limit: raise ValueError("Input exceeds the size limit.")
    return Path(path).read_bytes()
def message(path):
    return BytesParser(policy=policy.default).parsebytes(raw(path))
def messages(path):
    if Path(path).stat().st_size>100*1024*1024: raise ValueError("Mailbox exceeds 100 MiB.")
    box=mailbox.mbox(path,factory=lambda f:BytesParser(policy=policy.default).parse(f),create=False)
    try:
        result=[]
        for msg in box:
            if len(result)>=5000: raise ValueError("Mailbox exceeds 5000 messages.")
            result.append(msg)
        return result
    finally: box.close()
def text_body(msg):
    part=msg.get_body(preferencelist=("plain",))
    return part.get_content() if part else ""
def address_pairs(msg,headers=("from","to","cc","bcc","reply-to")):
    return getaddresses([str(v) for key in headers for v in msg.get_all(key,[])])
def attachments(msg):
    return [p for p in msg.walk() if p.get_content_maintype()!="multipart" and (p.get_content_disposition()=="attachment" or p.get_filename() is not None)]
def payload(part):
    if part.get_content_type()=="message/rfc822" and isinstance(part.get_payload(),list):
        return part.get_payload(0).as_bytes(policy=policy.default)
    return part.get_payload(decode=True) or b""
def save_message(path,msg):
    data=msg.as_bytes(policy=policy.SMTP)
    with Path(path).open("xb") as handle: handle.write(data)
def clean_address(value):
    if "\r" in value or "\n" in value: raise ValueError("Address cannot contain newlines.")
    display,address=parseaddr(value)
    if "@" not in address or any(c.isspace() for c in address): raise ValueError("Supply one ordinary email address.")
    return address
def draft(sender,recipient,subject,body):
    msg=EmailMessage()
    msg["From"]=clean_address(sender)
    msg["To"]=clean_address(recipient)
    msg["Subject"]=subject
    msg["Date"]=format_datetime(datetime.now(timezone.utc))
    msg["Message-ID"]=make_msgid(domain="scriptage.local")
    msg.set_content(body)
    return msg

def main():
    parser = argparse.ArgumentParser(description='Create a quoted local reply draft')
    parser.add_argument("--input",required=True,help="Local EML, MBOX, or body file as documented")
    parser.add_argument("--output",required=True,help="New result file or directory")
    parser.add_argument("--from-address",required=True)
    parser.add_argument("--intro",default="Thanks for the update.")
    args = parser.parse_args()
    original=message(args.input)
    recipient=str(original.get("Reply-To") or original.get("From") or "")
    subject=re.sub(r"^(?:(?:re|fw|fwd)\s*:\s*)+","",str(original.get("Subject","")),flags=re.I)
    quoted="\n".join("> "+line for line in text_body(original)[:50000].splitlines())
    reply=draft(args.from_address,recipient,"Re: "+subject,args.intro+"\n\n"+quoted+"\n")
    identifier=str(original.get("Message-ID",""))
    if identifier:
        reply["In-Reply-To"]=identifier
        reply["References"]=(" ".join(str(v) for v in original.get_all("References",[]))+" "+identifier).strip()
    save_message(args.output,reply)

if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, KeyError, TypeError, ArithmeticError, IndexError, LookupError) as exc:
        raise SystemExit(str(exc))

Open source as plain text · Download source and sample files

How it works

  1. All messages are read from local files; no SMTP, browser, or email-service connection is used.
  2. The reply targets Reply-To when present, otherwise From; no reply-all recipients or attachments are copied.
  3. The fixture draft is from Bo to Ada and starts with Thanks for the update.

Make it your own

--intro

Change --intro to your own opening sentence.

Adapt the processing

Edit main's 50000-character quotation limit if a shorter excerpt is preferable.

Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.

If something goes wrong

No valid sender address is available.

Inspect the original From and Reply-To headers; the tool requires one ordinary recipient address.

The destination already exists.

Choose a new --output path. The script deliberately refuses to replace an existing result.

Reference & next steps

These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.

Copies a template for your own notes. It does not send anything.