User avatar
williamhbell
Posts: 291
Joined: Mon Dec 26, 2011 5:13 pm
Contact: Website Twitter

Re: Getting the Pi to send an e-mail

Sat May 24, 2014 12:23 am

All of the configuration file changes can be avoiding by using python's smtp library,

Code: Select all

#!/usr/bin/env python
# A program to send an email with gmail
import smtplib
from email.mime.text import MIMEText

def sendGmail(fromaddr, toaddr, username, password, 
              email_body, email_subject):          

  # Build the email
  msg = MIMEText(email_body)
  msg['Subject'] = email_subject
  msg['From'] = fromaddr
  msg['To'] = toaddr

  try:
    # The actual mail send
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddr, msg.as_string())  
    server.quit()
    print "email sent: %s" % fromaddr
  except Exception as e:
    print "Something went wrong when sending the email %s" % fromaddr
    print e

fromaddr = 'someuser@gmail.com'
toaddrs  = 'tosomeone@aol.com'
msg = 'This is a text message...'
msgSubject = 'Test message'
username = 'someuser@gmail.com'
password = 'xxxxxxxx'

sendGmail(fromaddr, toaddrs, username, password, msg, msgSubject)

Return to “Teaching and learning resources”