Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

Generate emails with mailto URLs and Python

[2009-02-14] dev, python
(Ad, please don’t block)

Scenario: You want to send several emails where only small things change. This sounds like a job for a mail merge program. But if you use mailto: links and Python, you get a nice shell-based solution. This combination also has the advantage of opening each generated email in your email client so that you can take one last look before sending it.

mailto: URL syntax

"mailto:" recipients ( "?" key "=" value ("&" key "=" value)* )?

Open mailto URLs with Python

    from urllib import quote
    import webbrowser

    def mailto(recipients, subject, body):
        "recipients: string with comma-separated emails (no spaces!)""mailto:%s?subject=%s&body=%s" %
            (recipients, quote(subject), quote(body)))

    body_template = """Hello %(name)s!

    How are you?"""

    def gen(email, name):
        mailto(email, "Hi!", body_template % locals())

    gen("", "Joe")
    gen(",", "Jane and Jill")