Here’s how you can communicate using Python!

DSP
Techloop
Published in
10 min readJul 1, 2020

Python is one of the fastest-growing major programming languages in the 21st century. It’s easy to learn, improves the productivity of programmers, has extensive support libraries and can be used for a variety of applications. From web development to software development, Python’s got it all covered.

Python is wonderful for automating day-to-day tasks like sending emails or even sending Whatsapp messages.

How often have you forgotten to wish your best friend on his or her birthday because you were occupied with some urgent chore? How often have you forgotten to wish a relative on his or her marriage anniversary?

If you’re a teacher wishing to remind your students to submit their assignments on time or if you want to advertise your event to hundreds of people automatically without personally typing out each email, Python’s got your back for all your tasks.

Your imagination is the limit.

SETTING UP YOUR GMAIL ACCOUNT

Let’s dive right in and see how we can send emails using Python. throughout this section, I’ll be using Gmail because it’s one of the most popular email services out there.

Also, for this task, I would suggest you create a separate/temporary Gmail account. You’ll be using this account to send the mail to your main account.

NOTE: If your Google account has 2-factor authentication enabled (yes, that irritating thing that asks for an OTP every time you log in and which is a pain but you do it anyway to keep your account safer), you’ll need to skip the steps below and go to the part where I address 2-factor authentication and follow those steps instead to work-around the additional security.

Once you have finished creating your new Gmail account, follow the instructions that follow to configure it to allow Python to access your Gmail.

STEP — 1: Go to your Google account page.

STEP — 2: Go to the Security option

You should arrive at this page.

STEP — 3: Scroll down till you see the option to “Less secure app access”. Click on that option and you’ll see a page like this.

You should arrive at this page.

STEP — 4: Turn “Allow less secure apps” to ON.

Alternatively, you can also click the hyperlink to go directly to the less secure apps page for your account.

Here’s what you need to do if you have 2-factor authentication enabled.

STEP — 1: In your Google Account page, go down to the Security option.

STEP — 2: Scroll down and search for Signing in to Google. You’ll notice an option called App passwords. So click that and set up an app password for “Mail on my Windows” / “Mail on my Mac” / “Mail on my Linux”.

STEP — 3: Copy that app password that Google generates for your app and we are ready to use this app password in our Python program to log in normally without any issues.

So, in hindsight, having a separate Gmail account will assure you that you’re not gonna mess with your main account in any way.

Now, I would like you to open your editor of choice for a small code-along session.

GETTING STARTED WITH THE CODE…

Sending a classic email (just some text)

import smtplib
smtpObject = smtplib.SMTP('smtp.gmail.com', 587)
smtpObject.starttls()

To send mails, we utilize a protocol known as SMTP.

SMTP is short for Simple Mail Transfer Protocol which handles email services and routing emails between different mail servers. SMTP dictates how email messages should be formatted, encrypted and relayed between mail servers and all the other details that your computer handles after you hit the “SEND” button.

Python provides the smtplib 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.

So, the first step is to import this module into our Python program.

Now, once you’ve imported the smtplib module, the next step is to connect to an SMTP Server. Here is a list of common email providers and their SMTP Servers.

Once you have chosen your domain name, you need to create an SMTP object by calling the SMTP method of the smtplib module.

You need to pass the domain name and the port number as arguments to the SMTP() method.

If this line of code fails to execute (probably because your SMTP server might not allow TLS on the port 587), you will need to use a different method (function) of the smtplib module to connect to the server.

smtpObject = smtplib.SMTP_SSL(‘smtp.gmail.com’, 465)

This line of code should do the trick. The SSL at the end stands for Secure Sockets Layer.

If you were unable to understand the technical jargon I was blabbering above, then, don’t worry; I’ll clear it all up for you in a bit.

Transport Layer Security or TLS for short is a widely adopted security protocol designed to facilitate privacy or data security for communications over the internet. BaIt’ssed to encrypt data for security purposes during communication.

Secure Sockets Layer or SSL is the deprecated predecessor of TLS. It performs the same task as TLS but is less secure. TLS has replaced SSL but the latter is still used for some communication purposes.

So, coming back to the code, if you used SMTP_SSL(), then you can skip the line of code that follows it, otherwise not.

starttls puts your SMTP connection in TLS mode. You don't need to follow this step if you used SMTP_SSL() because it configures your connection to use SSL instead of TLS.

Now, we’re pretty much done with the boring task of setting up the SMTP connection. Let’s move on to logging in to your Gmail account (the temporary one!).

smtpObject.login('your_temporary_account@gmail.com',
'your_secret_password')
smtpObject.sendmail('your_temporary_account@gmail.com',
'recipient@example.com',
'Subject: This is a test mail.\n Lorem ipsum
dolor sit amet. Hello, Goodbye. Thanks Charles')
smtpObject.quit()

So to log in, we use another method of the smtplib object that we just created and that is the login() method. Yes, it’s pretty obvious and so, it’s easy to remember!

The login() method takes in 2 arguments — the email id and the password for your email. “your_secret_password” is your account password or if you have 2-factor authentication enabled, then use your app password which you created earlier.

A TIP: Never put your password in your code. It is much safer to call Input() and to type it out when you need it. You never know how some attacker might get access to your code and then easily access your mail and steal/damage your data.

Once that line of code is executed and you are successfully logged in, your job is 90% done.

The next step is to send an email using the sendmail() method of the smtplib object.

The sendmail() method takes in 3 arguments. The first one is the sender’s address, the second one is the receiver’s address and the third one is the Subject and the body of the mail. The “\n” (carriage return character) separates the Subject from the body of the mail.

This method (sendmail()) does exactly what it says. It sends the mail.

After this, we just need to do one last thing and that is to disconnect from the SMTP Server by calling the quit() method of the smtplib object.

And that’s it! You’ve successfully sent your first mail using Python! You can now utilise this in interesting applications like automatically sending bulk mails (there is a 100 mails limit but that’s good enough for experimental purposes) or sending emails to notify you about your upcoming tasks…. As I said, your imagination is the limit.

Sending an attachment with your email

Okay! Time to level up. Let’s try sending an attachment.

NOTE: Before we begin, download any image from the internet and store it in the same directory as your Python program. This is what we will be attaching to the mail.

smtplib is great for the classic email. A subject, some text, a signature… but that’s it. It cannot do more than that. So, to send attachments, you need something else. That’s why we are bringing in another built-in module: The email module.

So let’s go ahead and import stuff from this module into our new program!

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os # to find the attachment

If you’re having trouble understanding what all this is, I would suggest you relax because I’ll be explaining everything as I go on.

MIME stands for Multipurpose Internet Mail Extensions. It’s something that facilitates the transfer of text or non-text attachment in mails. The term multipart signifies that I am going to split up the entire email into segments and I’m going to fill out every segment individually. In the end, I’m going to bring them all together and join them all up into one beautiful email. Sounds good?

Doing such a thing kind of gives you more control on filling up the mail, as you might notice.

from_address = input("Enter your email ID : ")
to_address = input("Enter the email id of the recipient : ")
msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = input('enter the subject of the mail : ')

First, we need to get the sender’s email id and the receiver’s email id by user input.

After that, we create an object/instance of the MIMEMultipart class by calling the MIMEMultipart() method.

NOTE: If you are unfamiliar with the word “object”, I suggest you check out some basics of object-oriented programming.

Now, we fill up three of the most important segments of a mail. Namely, the sender’s address, the receiver’s address and the subject of the mail.

If you are familiar with dictionaries in Python, you might be thinking that this kind of looks like msg is a dictionary. However, I did initialize msg as an instance of MIMEMultipart class, right?

Check this wonderful work going on behind the scenes.

Let’s print msg to see what it is. Let’s go to the console.

>>print(msg)
Content-Type: multipart/mixed; boundary="===============8405393699006628054=="
MIME-Version: 1.0
From: my_temporary_mail@gmail.com
To: another_temp_mail@gmail.com
Subject: This is a test mail
--===============8405393699006628054==--===============8405393699006628054==--

You can see that the parts like From, To and Subject are well listed in msg.

Let’s now access two methods of the MIMEMultipart class, through msg. These two methods are the “keys()” and the “items()” methods.

>>print(msg.keys())
['Content-Type', 'MIME-Version', 'From', 'To', 'Subject']
>>print(msg.items())
[('Content-Type', 'multipart/mixed; boundary="===============8405393699006628054=="'), ('MIME-Version', '1.0'), ('From', 'my_temporary_mail@gmail.com'), ('To', 'another_temp_mail@gmail.com'), ('Subject', 'This is a test mail')]

So msg provides a “dictionary-like” experience by innovatively utilising two different lists. One list holds the keys and the other holds the values/items!

Coming back to the editor, type in the following code snippet.

body = input("Enter the body of the mail : ")
msg_text = MIMEText(body, 'plain')
msg.attach(msg_text)
filename = 'Your_attachment.jpg'
attachment = open(os.getcwd() + r'/' + filename, "rb")

Let’s get the body of the mail ready now. The body is a string which is not a MIME object, which is why it is incompatible with the MIMEMultipart object, msg. So, we need to convert it into a MIME text so that we can add this into our MIMEMultipart object. We do that by utilising the MIMEText class. Simple enough. We add this MIME text into msg by using the attach() method of the MIMEMultipart Object.

And finally, we need to attach the attachment with our MIMEMultipart object.

For this we first need to open the file we plan to attach, by using the open() method. The term at the end “rb” is used to open the file in binary format. This is because to allow the file to be attached with the MIMEMultipart object, we need to encode it into a form so that the MIMEMultipart object can understand it as an attachment and can upload it automatically from your computer when you generate the mail.

p = MIMEBase('Application', 'octet-stream')
p.set_payload((attachment).read())
encoders.encode_base64(p)
p.add_header('Content-Disposition',
'attachment; filename= %s'%filename)
msg.attach(p)
text = msg.as_string()

After opening the attachment, we need to attach it to our email. To do that we first need to encode the binary file we just opened into Base64 format. And what is base64 you ask? According to Wikipedia, Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format. The term Base64 originates from a specific MIME content transfer encoding.

The set_payload() method of the MIMEBase object that we create is kind of self-explanatory. The argument that it takes in is the file that we just opened in binary format.

And we’re done! We attach this attachment along with our MIMEMultipart object by using the attach() method and lastly, we convert that MIMEMultipart object, msg, into a string so that we can easily add it to our mail using the smtplib module’s sendmail() method.

And the rest is the same as the classic email. Only this time in place of the body of the mail, all you have to do is to replace the entire subject and body of the mail with text, which we have created just now. And if you’re wondering, text will automatically take care of uploading the attachment, you don’t need to bother at all. It’s that convenient.

smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
smtpobj.starttls()
password = input("Enter your mail password : ")smtpobj.login(from_address, password)smtpobj.sendmail(from_address, to_address, text)smtpobj.quit()

And congratulations! You’ve just created your first mail with an attachment! And you can now experiment with this. Try putting multiple attachments if you want a challenge!

Whew! That was quite an adventure, wasn’t it?

Well, what are you waiting for? Pat yourself on the back! You’ve successfully sent a classic email as well as a fancy email using Python. You made it!

Well, my friend, I hope to see you soon, in the next part of this article as well, where we go on yet another adventure with Python, breaking the boundaries of boring, usual communication.

--

--

DSP
Techloop

An avid adventurer, wandering the magical land of Python!