I’m using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I’m missing ?
from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') from_addr = 'John Doe <john@doe.net>' to_addr = 'foo@bar.com' subj = 'hello' date = datetime.datetime.now().strftime( '%d/%m/%Y %H:%M' ) message_text = 'Hello\nThis is a mail from your server\n\nBye\n' msg = 'From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s' % ( from_addr, to_addr, subj, date, message_text ) smtp.sendmail(from_addr, to_addr, msg) smtp.quit()
The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.
I rely on my ISP to add the date time header.
My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)
As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.
=======================================