Question 7.15: You want to send an email message from a Python program....

You want to send an email message from a Python program.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Python has a library for the Simple Mail Transfer Protocol (SMTP) that you can use to send emails:

import smtplib
GMAIL_USER = ‘your_name@gmail.com’
GMAIL_PASS = ‘your_password’
SMTP_SERVER = ‘smtp.gmail.com’
SMTP_PORT = 587
def send_email(recipient, subject, text):
smtpserver = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(GMAIL_USER, GMAIL_PASS)
header = ‘To:’ + recipient + ‘\n’ + ‘From: ‘ + GMAIL_USER
header = header + ‘\n’ + ‘Subject:’ + subject + ‘\n’
msg = header + ‘\n’ + text + ‘ \n\n’
smtpserver.sendmail(GMAIL_USER, recipient, msg)
smtpserver.close()
send_email(‘destination_email_address’, ‘sub’, ‘this is text’)

To use this example to send an email to an address of your choice, first change the variables GMAIL_USER and GMAIL_PASS to match your email credentials. If you are not using Gmail, then you will also need to change the values of the SMTP_SERVER and possibly SMTP_PORT.

You will also need to change the destination email address in the last line.

Discussion

The send_email message simplifies the use of the smtplib library into a single function that you can reuse in your projects.

Being able to send emails from Python opens up all sorts of project opportunities. For example, you could use a sensor such as the PIR sensor of Recipe 11.9 to send an email when movement is detected.

See Also

For performing HTTP requests from the Raspberry Pi, see Recipe 7.13.

For more information on the smtplib, see http://docs.python.org/2/library/smtplib.html.

Related Answered Questions

Question: 7.14

Verified Answer:

Import sys and use its argv property, as shown in ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.16

Verified Answer:

Use the bottle Python library to run a pure Python...
Question: 7.11

Verified Answer:

Use the import command: import random Discus...
Question: 7.8

Verified Answer:

To read a file’s contents, you need to use the fil...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...
Question: 7.4

Verified Answer:

Define a class and provide it with the member vari...