Saturday 9 March 2013

Quickest Python Emailer

Hi Everyone,

Over the years I've written many scripts which end up sending an email report. Here is a short and sweet Python version, which has served me well a few times.
  1. This needs to run on a server which can send mail. (Many Unix or Linux will relay localhost with sendmail / postfix etc.)
  2. If you are sending to an external mail system, check your Spam / Junk folders. It may look suspicious, especially if you use a from address which is not the actual domain of the sending machine.
It's not wrapped in a class, or given any bells or whistles. It's just an easy way to send mail!

Enjoy.

'''
Created on 9 Mar 2013

@author: HRH

Probably the quickest way to send an email in python!

'''
import smtplib

SERVER  = "localhost"
FROM    = "Test_Script@myhost.co.uk"
TO      = ["joe_butler99@hotmail.com"] # must be a list
SUBJECT = "Test Mail from RoyalScripts"
TEXT    = "This message was sent with Python's smtplib."

# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)


# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()


No comments:

Post a Comment