Using SMTP with Python

1. Using the smtplib library

General workflow is:

  1. Create SMTP server object
  2. Connect/Login
  3. Sendmail
  4. Quit

You can combine (1) and (2).

2. Usage

   1 import smtplib
   2 
   3 from_email = 'xxx@example.com'
   4 to_email   = 'yyy@example.com'
   5 message = """From: %s
   6 To: %s
   7 Subject: Hello there
   8 
   9 What a nice day!
  10 """ % (from_email, to_email)
  11 
  12 # Simplest usage
  13 server=smtplib.SMTP('localhost')
  14 server.sendmail( from_email, [to_email], message)
  15 server.quit()
  16 
  17 # Longer form
  18 server=smtplib.SMTP()
  19 server.connect('localhost')
  20 server.sendmail( from_email, [to_email], message)
  21 server.quit()
  22 

3. Secured SMTP

   1 import smtplib
   2 
   3 # If using TLS
   4 server=smtplib.SMTP('localhost')
   5 server.starttls() # Do this before authentication
   6 server.sendmail( from_email, [to_email], message)
   7 server.quit()
   8 
   9 # If using SSL
  10 server=smtplib.SMTP_SSL('localhost')
  11 server.sendmail( from_email, [to_email], message)
  12 server.quit()
  13 

4. SMTP Client Authentication

   1 import smtplib
   2 
   3 # If using TLS
   4 server=smtplib.SMTP('localhost')
   5 server.starttls() # Do this before authentication
   6 server.login('username', 'password')
   7 server.sendmail( from_email, [to_email], message)
   8 server.quit()
   9 
  10 # If using SSL
  11 server=smtplib.SMTP_SSL('localhost')
  12 server.login('username', 'password')
  13 server.sendmail( from_email, [to_email], message)
  14 server.quit()
  15 

5. Exceptions

All smtplib exceptions are subclasses of smtplib.SMTPException

6. Debugging

To debug SMTP connection errors, set {server.set_debuglevel(1) before doing any SMTP transactions.

Python/SMTP (last edited 2010-09-11 18:37:16 by SandipBhattacharya)