Foundations of Python Network Programming

(WallPaper) #1

Chapter 12 ■ Building and parsing e-Mail


226


text = """Hello,
This is a basic message from Chapter 12.



  • Anonymous"""


def main():
message = email.message.EmailMessage(email.policy.SMTP)
message['To'] = '[email protected]'
message['From'] = 'Test Sender [email protected]'
message['Subject'] = 'Test Message, Chapter 12'
message['Date'] = email.utils.formatdate(localtime=True)
message['Message-ID'] = email.utils.make_msgid()
message.set_content(text)
sys.stdout.buffer.write(message.as_bytes())


if name == 'main':
main()


■ Caution the code in this chapter specifically targets python 3.4 and later, the version of python that introduced the


EmailMessage class to the old e-mail module. if you need to target older versions of python 3 and cannot upgrade, study


the older scripts at https://github.com/brandon-rhodes/fopnp/tree/m/py3/old-chapter12.


You can generate even simpler e-mail messages by omitting the headers shown here, but this is the minimal set
that you should generally consider on the modern Internet.
The API of EmailMessage lets your code reflect the text of your e-mail message very closely. Although you are free
to set headers and provide the content in any order that makes the best sense of your code, setting the headers first
and then setting the body last provides a pleasing symmetry with the way the message will appear both on the wire
and also when viewed in an e-mail client.
Note that I am setting two headers here that you should always include, but whose values will not be set for you
automatically. I am providing the Date in the special format required by the e-mail standards by taking advantage of
the formatdate() function that is already built in to the standard set of e-mail utilities in Python. The Message-Id is
also carefully constructed from random information to make it (hopefully) unique among all of the e-mail messages
that have ever been written in the past or that will ever be written in the future.
The resulting script simply prints the e-mail on its standard output, which makes it very easy to experiment with
and immediately shows the results of any edits or modifications you made.


To: [email protected]
From: Test Sender [email protected]
Subject: Test Message, Chapter 12
Date: Fri, 28 Mar 2014 16:54:17 -0400
Message-ID: 20140328205417.5927.96806@guinness
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0


Hello,
This is a basic message from Chapter 12.



  • Anonymous

Free download pdf