Monday 6 February 2012

Python - Sending emails using smtplib


Here is a snippet that will send emails to one or more recipients. It will also send the name alongside the FROM email address.

Just plug in the SMTP server details and toggle AUTH if required.


Send an email to one or more recipients
Code Snippet
  1. import smtplib
  2. import email.utils
  3. from email.mime.text import MIMEText
  4. from email.utils import formataddr
  5.  
  6.  
  7. def emailer():
  8.  
  9.             # Email Settings
  10.             MESSAGEBODY = 'Test Email body.'
  11.             SUBJECT = 'Test Email Subject'
  12.             FROM = ('Some User', 'donotreply@someurl.com')
  13.             TO = ['recipient1@someurl.com', 'recipient2@someurl.com']
  14.  
  15.             # SMTP Settings
  16.             smtpserver = 'SMTP SERVER ADDRESS'
  17.             smtpport = 25
  18.             AUTHREQUIRED = 0   # If you need to use SMTP AUTH set to 1
  19.             smtpuser = 'foo'  # For SMTP AUTH, set SMTP username here
  20.             smtppass = 'bar'   # For SMTP AUTH, set SMTP password here
  21.  
  22.             # Create the message
  23.             msg = MIMEText(MESSAGEBODY)
  24.             msg['To'] = ', '.join(TO)
  25.             msg['From'] = email.utils.formataddr(FROM)
  26.             msg['Subject'] = SUBJECT
  27.            
  28.             try:
  29.                 smtpObj = smtplib.SMTP(smtpserver, smtpport)
  30.            
  31.                 if AUTHREQUIRED:
  32.                     session.login(smtpuser, smtppass)
  33.            
  34.                 smtpObj.sendmail(msg['From'], TO, msg.as_string())
  35.                
  36.                 print "Email has been sent successfully to: " + msg['To']
  37.             except Exception, err:
  38.                 print "Error: unable to send error email notification. %s"  % str(err)
  39.  
  40.  
  41.  
  42. # Invoke Emailer
  43. emailer()
End of Code Snippet

Python Email Examples
http://docs.python.org/library/email-examples.html

No comments: