Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending mail via sendmail from python

If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?

Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?

I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP.

As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to popen('/usr/bin/sendmail', 'w') is a little closer to the metal than I'd like.

If the answer is 'go write a library,' so be it ;-)

like image 365
Nate Avatar asked Sep 16 '08 15:09

Nate


People also ask

How do I send an email using Python?

Set up a secure connection using SMTP_SSL() and .starttls() Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package. Send multiple personalized emails using a CSV file with contact data.

How do I send an email using sendmail?

Once logged in, you can run the following command to send email: [server]$ /usr/sbin/sendmail [email protected] Subject: Test Send Mail Hello World control d (this key combination of control key and d will finish the email.)


2 Answers

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 sys from email.mime.text import MIMEText from subprocess import Popen, PIPE   msg = MIMEText("Here is the body of my message") msg["From"] = "[email protected]" msg["To"] = "[email protected]" msg["Subject"] = "This is the subject." p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) # Both Python 2.X and 3.X p.communicate(msg.as_bytes() if sys.version_info >= (3,0) else msg.as_string())   # Python 2.X p.communicate(msg.as_string())  # Python 3.X p.communicate(msg.as_bytes()) 
like image 105
Jim Avatar answered Sep 27 '22 23:09

Jim


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" % "[email protected]")     p.write("To: %s\n" % "[email protected]")     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 
like image 37
Pieter Avatar answered Sep 28 '22 01:09

Pieter