# 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 `smtplib` 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.

``` python
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
```

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.

``` python
server.ehlo()
server.starttls()
server.ehlo()
```

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:

``` python
server.login("youremailusername", "password")
```

Then, send the mail:

``` python
msg = "\nHello!" # The /n separates the message from the headers (which we ignore for this example)
server.sendmail("you@gmail.com", "target@example.com", msg)
```

Note that this is a rather crude example, it doesn\'t include a subject,
or any other headers. For that, one should use the `email` package.

## The `email` 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.

``` python
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
```

Then we compose some of the basic message headers:

``` python
fromaddr = "you@gmail.com"
toaddr = "target@example.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Python email"
```

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

``` python
body = "Python test mail"
msg.attach(MIMEText(body, 'plain'))
```

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..

``` python
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("youremailusername", "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
```

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:


