How to send email through Gmail in Python

As part of my job, I have to send regular reports to my clients. I use Gmail for sending/receiving emails from my clients. I thought it would be really easy if I could write a software to automatically send the report in Python. In this tutorial, we will learn How to send email through Gmail in Python.


Example : At the end of this tutorial, you will learn how to send an email to multiple recipients. You would attach the document in the email before sending to the recipient.

Step 1 : Login to Gmail

We use smtplib library in Python to login to Gmail. You can use the following code to login to Gmail.


Step 2 : Prepare the message

Please note you can send a simple text message as well as HTML. It is much better to prepare email templates in HTML and replace the placeholders with relevant information in the templates.


Step 3 : Attach Files

Suppose you want to attach  2 files while sending the email. This can be using MIME package in Python


Step 4 : Send Email

The last step is to send the email using sendmail() of smtplib library.

 

Download

The complete Python source can be downloaded from here. Please note, that the code is tested using Python 2.7 . If you are using Python 3.3, you might have to do some minor changes in the code.

I hope, you find this article very useful. If you have any doubts or have any comments concerning this tutorial, Please leave a comment or contact me. I would be glad to help.




Kiran Chandrashekhar

Hey, Thanks for dropping by. My name is Kiran Chandrashekhar. I am a full-time software freelancer. I love Maths and Mathematical Shortcuts. Numbers fascinate me. I will be posting articles on Mathematical Shortcuts, Software Tips, Programming Tips in this website. I love teaching students preparing for various competitive examinations. Read my complete story.

Leave a Reply

Your email address will not be published. Required fields are marked *

Protected by WP Anti Spam