Sending mail via sendmail from python Sending mail via sendmail from python python python

Sending mail via sendmail from python


Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the email package, construct the mail with that, serialise it, and send it to /usr/sbin/sendmail using the subprocess module:

import sysfrom email.mime.text import MIMETextfrom subprocess import Popen, PIPEmsg = MIMEText("Here is the body of my message")msg["From"] = "me@example.com"msg["To"] = "you@example.com"msg["Subject"] = "This is the subject."p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)# Both Python 2.X and 3.Xp.communicate(msg.as_bytes() if sys.version_info >= (3,0) else msg.as_string()) # Python 2.Xp.communicate(msg.as_string())# Python 3.Xp.communicate(msg.as_bytes())


This is a simple python function that uses the unix sendmail to deliver a mail.

def sendMail():    sendmail_location = "/usr/sbin/sendmail" # sendmail location    p = os.popen("%s -t" % sendmail_location, "w")    p.write("From: %s\n" % "from@somewhere.com")    p.write("To: %s\n" % "to@somewhereelse.com")    p.write("Subject: thesubject\n")    p.write("\n") # blank line separating headers from body    p.write("body of the mail")    status = p.close()    if status != 0:           print "Sendmail exit status", status


Jim's answer did not work for me in Python 3.4. I had to add an additional universal_newlines=True argument to subrocess.Popen()

from email.mime.text import MIMETextfrom subprocess import Popen, PIPEmsg = MIMEText("Here is the body of my message")msg["From"] = "me@example.com"msg["To"] = "you@example.com"msg["Subject"] = "This is the subject."p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE, universal_newlines=True)p.communicate(msg.as_string())

Without the universal_newlines=True I get

TypeError: 'str' does not support the buffer interface