Sunday, March 09, 2008

Python: script for sending email

Function for sending emails using Python script. It requires local SMTP server (e.g. Postfix) or one can provide address to the external SMTP server.

def mail(From,To,subject,msg):
import smtplib

smtpserver = 'localhost' # SMTP server
AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1
smtpuser = '' # for SMTP AUTH, set SMTP username here
smtppass = '' # for SMTP AUTH, set SMTP password here

RECIPIENTS=To
SENDER=From

mssg = """"\From: %s
Subject: %s
%s
""" %(SENDER,subject,msg)

session = smtplib.SMTP(smtpserver)
if AUTHREQUIRED:
session.login(smtpuser, smtppass)
smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
session.quit()


if __name__ == '__main__':
subject="This is some email subject"
mssg='This is content of the mail.'
mail("return@address.com","destination@address.com",
subject,mssg)
Note: this code is based on the this article.