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:

  • host: This is the IP address or domain of the SMTP server host
  • port: The default value is 25 and, if you provide a host parameter, you need to specify the port number that's used by the SMTP server
  • local_hostname: You need to specify the localhost server address if your SMTP server is located on your local machine sendmail  has the following syntax and parameters:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

Let's look at these parameters in detail:

  • from_addr: The sender's email address
  • to_addrs: A list of chains; sends an email
  • msg: Sends a message
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset