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.
import smtplib # your Gmail account
s = 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:
- The sender – A string with the address of the sender.
- The receivers – A list of strings, one for each recipient.
- The message – A message as a string formatted as specified in the various RFCs.
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