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.
1
2
3
4
5
6
|
server = smtplib.SMTP("smtp.gmail.com", 587) #or port 465 doesn't seem to work!
server.ehlo()
server.starttls()
gmail_user = 'kiran.chandrashekhar'
gmail_pwd = 'gmail_password_here'
server.login(gmail_user, gmail_pwd)
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
msg = MIMEMultipart()
Subject = "Test Message"
# Message can be a simple text message or HTML
TEXT = "Hello everyone,\n"
TEXT = TEXT + "\n"
TEXT = TEXT + "Hope you are doing fine today.\n"
TEXT = TEXT + "Please review the attached documents and let me know if it looks it\n"
TEXT = TEXT + "\n"
TEXT = TEXT + "I would be glad to answer if you have any questions"
TEXT = TEXT + "\n"
TEXT = TEXT + "Thanks,\n"
TEXT = TEXT + "Kiran"
msg['To'] = ", ".join(to) #Join them as we have multiple recipients
msg['Subject'] = Subject
msg.attach(MIMEText(text))
|
Step 3 : Attach Files
Suppose you want to attach 2 files while sending the email. This can be using MIME package in Python
1
2
3
4
5
6
7
8
|
#Loop through all the attachment files filenames
for file in filenames:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(file, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
|
Step 4 : Send Email
The last step is to send the email using sendmail() of smtplib library.
1
2
3
|
server.sendmail(gmail_user, to, msg.as_string())
# Should be server.quit(), but that crashes...
server.close()
|
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.