How do I send mail from a Python script?
Use the standard smtplib module.
Here’s a simple example that creates a message body and sends it to one or more recipients. This method will work on any host that supports an SMTP listener.
import smtplib SERVER = "localhost" FROM = "firstname.lastname@example.org" TO = ["email@example.com"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP(SERVER) server.sendmail(FROM, TO, message) server.quit()
Note that the TO variable must be a list, and that you have to add the From, To, and Subject headers to the message yourself. The TO argument to the sendmail method is only used to route the message to the right recipients, and doesn’t have to match the headers in the message itself. This can be used to implement Bcc headers; to send a blind copy, add the address to the TO argument, but don’t include it in the To header.
A Unix-only alternative is to use the sendmail program directly. The location of the sendmail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The sendmail manual page will help you out. Here’s an example:
SENDMAIL = "/usr/sbin/sendmail" # sendmail location FROM = "firstname.lastname@example.org" TO = ["email@example.com"] SUBJECT = "Hello!" TEXT = "This message was sent via sendmail." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail import os p = os.popen("%s -t -i" % SENDMAIL, "w") p.write(message) status = p.close() if status: print "Sendmail exit status", status
The -t option tells sendmail to parse the message, and extract the necessary routing information itself.