Sending Email using SMTP

Sending Email : 

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

Python provides SMTP lib module which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.

Syntax : 

import smtplib                                                                                  # your Gmail account

= smtplib.SMTP(‘smtp.gmail.com’, 587)                                     # creates SMTP session

s.starttls()                                                                                            # start TLS for security

s.login(“sender_email_id”, “sender_email_id_password”)                # Authentication

message = “Message_you_need_to_send”                                          # message to be sent

s.sendmail(“sender_email_id”, “receiver_email_id”, message)     # sending the  mail

s.quit()                                                                                             # terminating the session

 Here is the detail of the parameters: 

  • Host :  

This is the host running your SMTP server. You can specify IP address of                                the host  or domain name. This is optional argument.

  • Port :  

If you are providing host argument then you need to specifiy a port where                           SMTP server is listening. Usually this port would be 25.

  • Local_Hostname :

If your SMTP server is running on your local machine then you can specify just                   localhost as of this option.

An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message.

It takes three parameters:

  1. The sender – A string with the address of the sender.
  1. The receivers – A list of strings, one for each recipient.
  2. The message – A message as a string formatted as specified in the various RFCs.

Example : 

Example-2 :

Important Points : 

  • This code can send simple mail which doesn’t have any attachment or any subject.
  • One most amazing thing about this code is that we can send any number of emails using this and Gmail always put your mail in the primary section. Mails send will not be Spam.
  • File handling can also be used to fetch email id from a file and further used for sending the emails.

 

 

– Rohit Sharma

 

 

 

About

Codec Networks provides IT Trainings from EC Council CEH ECSA, LPT, CHFI, Network Security, Penetration Testing, ISACA, ISC2, PECB ISO 27001LA LI, Cisco Networking CCNA CCNP, Linux Administration RHCE, Prog Languages JAVA, Advanced Java, android development. We also offer B2B Industry Solutions and Services in IT | Information|Cyber Security in Delhi NCR India.

View all posts by