Working with smtplib

Python provides the smtplib module for working with the SMTP protocol. You can transmit messages by calling the sendmail() method of SMTP objects. Let's look at how we can using it to send an email with this module:

  1. Create a smtplib.SMTP object that will receive as a parameter of its constructor method, that is, the host (localhost)
  2. Create a mail message
  3. Send the message through a call to the sendmail method of the SMTP object

The syntax for creating a SMTP object is as follows:

import smtplib
smtpObj = smtplib.SMTP([host[,port[,local_hostname]]])

Let's look at what each parameter in the preceding code in more detail:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

Let's look at these parameters in detail: