Archive - Originally posted on "The Horse's Mouth" - 2007-01-18 09:14:43 - Graham Ellis
Good question - came up on the course yesterday and all the examples I could find were longwinded or obfursacted to avoid them abusing the email addresses of the people named.
At the risk of getting lots of people trying this out and filling my mail box, here is a sample piece of code that emails grom graham@wellho.net to graham@sheepbingo.co.uk in Python, with the subject line "greeting from here" and the body just saying "Hello World".
# Emailing from Python
import smtplib
from email.MIMEText import MIMEText
# Set up a MIMEText object (it's a dictionary)
msg = MIMEText("Hello World")
# You can use add_header or set headers directly ...
msg['Subject'] = 'greeting from here'
# Following headers are useful to show the email correctly
# in your recipient's email box, and to avoid being marked
# as spam. They are NOT essential to the snemail call later
msg['From'] = "Graham J Ellis "
msg['Reply-to'] = "Graham Ellis "
msg['To'] = "graham@sheepbingo.co.uk"
# Establish an SMTP object and connect to your mail server
s = smtplib.SMTP()
s.connect("www.wellho.net")
# Send the email - real from, real to, extra headers and content ...
s.sendmail("graham@wellho.net","graham@sheepbingo.co.uk", msg.as_string())
s.close()
In our case, the machine I'm running the script on is not a mail server, so I've connected to a machine that is in the connect method. And, before you try it out, please note that our outgoing mail server is not an open relay. In other words you will need to change that to your own outgoing mail machine - it won't work for you one mine.