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:
- 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.
- The smtp protocol requires a smtp server so we are going to use gmail smtp server.
- 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('smtp.gmail.com', 587) server.ehlo() server.starttls() #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!" try: server.sendmail("your e-mail", "recipient email ", msg) except Exception as e: print e
Explanation of the Code:
- The first line imports the inbuilt smtplib library of python.
- Then we tell python that we are using google smtp server on port 587
- 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.
- Next we activate the Transport Layer Security for our SMTP connection.
- Next we login to google smtp server and then we create a message with hello in it.
- 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.
- Thus we can easily send email using python smtplib.
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.