Send Emails Using Python

Send mail from your Gmail account using Python

“smtplib” creates a Simple Mail Transfer ProtocolSMTP) client session object which is used to send emails to any valid email id on the internet. Different websites use different port numbers.

Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers.

Syntax to create one SMTP object:

 import smtplib

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

send an email message using the email package alone. You need a combination of both email and smtplib.

Basic steps for sending emails using Python:

  • Set up the SMTP server and log into your account.
  • Create the MIMEMultipart message object and load it with appropriate headers for From, To, and Subject fields.
  • Add your message body.
  • Send the message using the SMTP server object.

Example:

To send the mail you use smtpObj to connect to the SMTP server on the local machine and then use the sendmail method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren't always used to route mail).


Sending Mails using Gmail



Sending email Sample

 sendemail(from_addr    = '[email protected]', 
   to_addr_list = ['[email protected]'],
   cc_addr_list = ['[email protected]'], 
   subject      = 'Learn Python', 
   message      = 'Learning Python Email', 
   login        = 'xxxxxxx', 
   password     = 'XXXXX')

Sample Email Received

 sendemail(from_addr    = '[email protected]', 
   to_addr_list = ['[email protected]'],
   cc_addr_list = ['[email protected]'], 
   subject      = 'Learn Python', 
   message      = 'Learning Python Email', 
   login        = 'xxxxxxx', 
   password     = 'XXXXX')