Python Programming/Email

Python includes several modules in the standard library for working with emails and email servers.

Sending mail
Sending mail is done with Python's  using an SMTP (Simple Mail Transfer Protocol) server. Actual usage varies depending on complexity of the email and settings of the email server, the instructions here are based on sending email through Google's Gmail.

The first step is to create an SMTP object, each object is used for connection with one server.

The first argument is the server's hostname, the second is the port. The port used varies depending on the server.

Next, we need to do a few steps to set up the proper connection for sending mail. These steps may not be necessary depending on the server you connect to. ehlo is used for ESMTP servers, for non-ESMTP servers, use helo instead. See Wikipedia's article about the SMTP protocol for more information about this. The starttls function starts Transport Layer Security mode, which is required by Gmail. Other mail systems may not use this, or it may not be available.

Next, log in to the server:

Then, send the mail: Note that this is a rather crude example, it doesn't include a subject, or any other headers. For that, one should use the  package.

The package
Python's email package contains many classes and functions for composing and parsing email messages, this section only covers a small subset useful for sending emails.

We start by importing only the classes we need, this also saves us from having to use the full module name later.

Then we compose some of the basic message headers:

Next, we attach the body of the email to the MIME message:

For sending the mail, we have to convert the object to a string, and then use the same procedure as above to send using the SMTP server..

If we look at the text, we can see it has added all the necessary headers and structure necessary for a MIME formatted email. See MIME for more details on the standard: