Riaan's SysAdmin Blog

My tips, howtos, gotchas, snippets and stuff. Use at your own risk!


Python Inject SMTP

Sometimes I want to email from Python and this is pretty easy. Or even just testing mail flow I prefer this over good old "telnet host 25" since we have well constructed headers with smtplib.

import datetime
import os
import sys
import smtplib

def warnEmail(SMTPserver, Subject, Body):
 fromaddr = "rrosso@domain.com"
 #toaddrs = ["rcpt1@domain.com","rcpt2@domain.com"]
 toaddrs = ["hostmaster@domain.com"]

 msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs),Subject))
 server = smtplib.SMTP(SMTPserver)
 msg = msg + Body
 server.sendmail(fromaddr, toaddrs, msg)

SMTPserver =  'mailhost'
warnEmail(SMTPserver, "Test through " + SMTPserver , "Body test goes \n here!")


Bio Info for Riaan