You want to send an email message from a Python program.
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.