Python – Sending mail from Python using SMTP

python, smtp

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 SMTPimport datetimedebuglevel = 0smtp = SMTP()smtp.set_debuglevel(debuglevel)smtp.connect('YOUR.MAIL.SERVER', 26)smtp.login('[email protected]', 'PASSWORD')from_addr = "John Doe <[email protected]>"to_addr = "[email protected]"subj = "hello"date = "%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()

Best Solution

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

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.


#! /usr/local/bin/pythonSMTPserver = ''sender =     '[email protected]'destination = ['[email protected]']USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"# typical values for text_subtype are plain, html, xmltext_subtype = 'plain'content="""\Test message"""subject="Sent from Python"import sysimport osimport refrom smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)# old version# from email.MIMEText import MIMETextfrom email.mime.text import MIMETexttry:    msg = MIMEText(content, text_subtype)    msg['Subject']=       subject    msg['From']   = sender # some SMTP servers will do this automatically, not all    conn = SMTP(SMTPserver)    conn.set_debuglevel(False)    conn.login(USERNAME, PASSWORD)    try:        conn.sendmail(sender, destination, msg.as_string())    finally:        conn.quit()except:    sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message