Riaan's SysAdmin Blog

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

Python

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.

#!/usr/bin/python
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.set_debuglevel(1)
 server.sendmail(fromaddr, toaddrs, msg)
 server.quit()

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

admin

Bio Info for Riaan