Sending mail from Python using SMTP Sending mail from Python using SMTP python python

Sending mail from Python using SMTP


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.

=======================================

#! /usr/local/bin/pythonSMTPserver = 'smtp.att.yahoo.com'sender =     'me@my_email_domain.net'destination = ['recipient@her_email_domain.com']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


The method I commonly use...not much different but a little bit

import smtplibfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEText import MIMETextmsg = MIMEMultipart()msg['From'] = 'me@gmail.com'msg['To'] = 'you@gmail.com'msg['Subject'] = 'simple email in python'message = 'here is the email'msg.attach(MIMEText(message))mailserver = smtplib.SMTP('smtp.gmail.com',587)# identify ourselves to smtp gmail clientmailserver.ehlo()# secure our email with tls encryptionmailserver.starttls()# re-identify ourselves as an encrypted connectionmailserver.ehlo()mailserver.login('me@gmail.com', 'mypassword')mailserver.sendmail('me@gmail.com','you@gmail.com',msg.as_string())mailserver.quit()

That's it


Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me:

...smtp.connect('YOUR.MAIL.SERVER', 587)smtp.ehlo()smtp.starttls()smtp.ehlo()smtp.login('USERNAME@DOMAIN', 'PASSWORD')...