Foundations of Python Network Programming

(WallPaper) #1

Chapter 12 ■ Building and parsing e-Mail


238


def main():
message = email.message.EmailMessage(email.policy.SMTP)
message['To'] = 'Böðvarr [email protected]'
message['From'] = 'Eardstapa [email protected]'
message['Subject'] = 'Four lines from The Wanderer'
message['Date'] = email.utils.formatdate(localtime=True)
message.set_content(text, cte='quoted-printable')
sys.stdout.buffer.write(message.as_bytes())


if name == 'main':
main()


The output e-mail uses a special ASCII encoding of binary data for the To: header because of the special
characters inside it. Furthermore, following on from advice given earlier, note that by specifying a quoted-printable
content encoding for the body, you avoid generating a block of Base64 data and instead represent most of the
characters by their straight ASCII codes, as shown in the following results.


To: =?utf-8?b?QsO2w7B2YXJy?= [email protected]
From: Eardstapa [email protected]
Subject: Four lines from The Wanderer
Date: Fri, 28 Mar 2014 22:11:48 -0400
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
MIME-Version: 1.0


Hw=C3=A6r cwom mearg? Hw=C3=A6r cwom mago?
Hw=C3=A6r cwom ma=C3=BE=C3=BEumgyfa?
Hw=C3=A6r cwom symbla gesetu?
Hw=C3=A6r sindon seledreamas?


The display script successfully untangles all of this, since the email module does all of the decoding and
processing for us.


$ python3 build_unicode_email.py > email.txt
$ python3 display_email.py email.txt
From: Eardstapa [email protected]
To: Böðvarr [email protected]
Date: Tue, 25 Mar 2014 17:14:01 -0400
Subject: Four lines from The Wanderer


Hwær cwom mearg? Hwær cwom mago?
Hwær cwom maþþumgyfa?
Hwær cwom symbla gesetu?
Hwær sindon seledreamas?


If you ever want to investigate e-mail header encoding further, read the Python documentation for the lower-level
email.header module and, in particular, its Header class.

Free download pdf