Saturday, 20 July 2013

How to send Email using Python using SMTP Server

The following tutorial showcases the use of python to send email using Google smtp server. Now if you have a gmail account then the following steps will guide you to achieve our objective to send email using Python:

  1. The library we are going to use is python smtplib. Python's smtplib is a library that supports sending of email using smtp protocol.That is Simple Mail Transfer Protocol.
  2. The smtp protocol requires a smtp server so we are going to use gmail smtp server.
  3. You can also use other free smtp server but i prefer google over any other services..:) Now the following code snippet will show you how to send a simple email using this service.
import smtplib
server = smtplib.SMTP('', 587)
#Now, log in to the google smtp server
server.login("your google e-mail id", "your password")
#Create the message to send mail
msg = "\nHello!" 
 server.sendmail("your e-mail", "recipient email ", msg)
except Exception as e:
 print e

Explanation of the Code:

  1. The first line imports the inbuilt smtplib library of python.
  2. Then we tell python that we are using google smtp server on port 587
  3. Next up we call the ehlo command that is a part of ESMTP protocol and this command is used to initiate communication it is pretty much same as helo.
  4. Next we activate the Transport Layer Security for our SMTP connection.
  5. Next we login to google smtp server and then we create a message with hello in it.
  6. Then we call the sendmail() method to send email it takes your email, recipient email, message that we created as argument we put this block under try and except clause to catch the raised exception if any.
  7. Thus we can easily send email using python smtplib.
Now you will be thinking why not open gmail and send email but with python what you can do is send
emails to multiple recipients and you can also use Cron Jobs to send emails in a timely manner
and use this tool extensively to send Marketing and Advertising Emails.

Ads :Online Shopping from eBay is a wonderful site that allows you to have a unique shopping experience
check out the auctions here

No comments:

Post a Comment