Programmatically sending an email is really a good tool for developer’s paraphernalia. This is really handy when one automates task and wants to get notified by an email for success or failure. Lately I have written Python script to automate some jobs and incorporated method to send email notification. I thought to share this simple script here so my readers can get benefited.
#!/usr/bin/env python import smtplib from email.mime.text import MIMEText EMAIL_SUBJECT = "Email from Python script" EMAIL_FROM = "[email protected]" EMAIL_RECEIVERS = ['[email protected]'] def listToStr(lst): """This method makes comma separated list item string""" return ','.join(lst) def getCurrentTime(): return datetime.now().strftime(DB_DATE_FORMAT) def send_email(msg): """This method sends an email""" msg_header = "From: " + EMAIL_FROM + "\n" + \ "To: " + listToStr(EMAIL_RECEIVERS) + "\n" + \ "Subject: " + EMAIL_SUBJECT + "\n" msg_body = msg_header + msg try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body) except SMTPException as error: print "Error: unable to send email : {err}".format(err=error) def main(): """This is a simple main() function which demonstrate sending of email using smtplib.""" send_email("Test email was generated by Python using smtplib and email libraries"); if __name__ == "__main__": """If this script is run as stand alone then call main() function.""" main()
Before running this script make sure your system has Mail Transfer Agent(MTA) configured. If it is not then read this post to configure Mail-server on Ubuntu 12.04. You can also get the source code from github/code4reference.
Hope this blog helped you in some way. If you like this blog then please share it. You can also leave your comment below. You can find Facebook page here.