Learning Python Network Programming

(Sean Pound) #1
Chapter 4

Composing an e-mail message


Let us construct the e-mail message by using classes from the email module. The
email.mime module provides classes for creating the e-mail and MIME objects from
scratch. MIME is an acronym for Multi-purpose Internet Mail Extensions. This is an
extension of the original Internet e-mail protocol. This is widely used for exchanging
different kinds of data files, such as audio, video, images, applications, and so on.


Many classes have been derived from the MIME base class. We will use an SMTP
client script using email.mime.multipart.MIMEMultipart() class as an example.
It accepts passing the e-mail header information through a keyword dictionary. Let's
have a look at how we can specify an e-mail header by using the MIMEMultipart()
object. Multi-part mime refers to sending both the HTML and the TEXT part of
an e-mail message in a single e-mail. When an e-mail client receives a multipart
message, it accepts the HTML version if it can render HTML, otherwise it presents
the plain text version, as shown in the following code block:


from email.mime.multipart import MIMEMultipart()
msg = MIMEMultipart()
msg['To'] = recipient
msg['From'] = sender
msg['Subject'] = 'Email subject..'

Now, attach a plain text message to this multi-part message object. We can wrap
a plain-text message by using the MIMEText() object. The constructor of this class
takes the additional arguments. For example, we can pass text and plain as its
arguments. The data of this message can be set by using the set_payload() method,
as shown here:


part = MIMEText('text', 'plain')
message = 'Email message ....'
part.set_payload(message)

Now, we will attach the plain text message to the Multi-part message, as shown here:


msg.attach(part)

The message is ready to be routed to the destination mail server by using one or
more SMTP MTA servers. But, obviously, the script only talks to a specific MTA
and that MTA handles the routing of the message.

Free download pdf