09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 12 ■ E-MAIL COMPOSITION AND DECODING<br />

The program is simple. It creates a Message object, sets the headers and body, and prints the result.<br />

When you run this program, you will get a nice formatted message with proper headers. The output is<br />

suitable for transmission right away! You can see the result in Listing 12–3.<br />

Listing 12–3. Printing the E-mail to the Screen<br />

$ ./trad_gen_simple.py<br />

To: recipient@example.com<br />

From: Test Sender <br />

Subject: Test Message, Chapter 12<br />

Hello,<br />

This is a test message from Chapter 12. I hope you enjoy it!<br />

-- Anonymous<br />

While technically correct, this message is actually a bit deficient when it comes to providing enough<br />

headers to really function in the modern world. For one thing, most e-mails should have a Date header,<br />

in a format specific to e-mail messages. <strong>Python</strong> provides an email.utils.formatdate() routine that will<br />

generate dates in the right format.<br />

You should add a Message-ID header to messages. This header should be generated in such a way<br />

that no other e-mail, anywhere in history, will ever have the same Message-ID. This might sound<br />

difficult, but <strong>Python</strong> provides a function to help do that as well: email.utils.make_msgid().<br />

So take a look at Listing 12–4, which fleshes out our first sample program into a more complete<br />

example that sets these additional headers.<br />

Listing 12–4. Generating a More Complete Set <strong>of</strong> Headers<br />

#!/usr/bin/env python<br />

# <strong>Foundations</strong> <strong>of</strong> <strong>Python</strong> <strong>Network</strong> <strong>Programming</strong> - Chapter 12 - trad_gen_newhdrs.py<br />

# Traditional Message Generation with Date and Message-ID<br />

# This program requires <strong>Python</strong> 2.5 or above<br />

import email.utils<br />

from email.message import Message<br />

message = """Hello,<br />

This is a test message from Chapter 12. I hope you enjoy it!<br />

-- Anonymous"""<br />

msg = Message()<br />

msg['To'] = 'recipient@example.com'<br />

msg['From'] = 'Test Sender '<br />

msg['Subject'] = 'Test Message, Chapter 12'<br />

msg['Date'] = email.utils.formatdate(localtime = 1)<br />

msg['Message-ID'] = email.utils.make_msgid()<br />

msg.set_payload(message)<br />

print msg.as_string()<br />

That’s better! If you run the program, you will notice two new headers in the output, as shown in<br />

Listing 12–5.<br />

201

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!