Skip to content

Python inject smtp

wordpress meta

title: 'Python Inject SMTP'
date: '2012-11-06T23:14:37-06:00'
status: publish
permalink: /python-inject-smtp
author: admin
excerpt: ''
type: post
id: 75
category:
    - Python
tag: []
post_format: []

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!")