Writing code to send emails

Today, I will be sharing on how to send emails using Python and Gmail. As the code is easily customizable, we can easily change how we send the email to the receivers. The full code can be found at: https://github.com/anwesh-b/Python-Email/blob/master/emails.py

Understanding the code:

Let’s create a file to store the list of receivers and a file to store message to be sent.

Receiver file

Message text

Now we need to read these files in our main code.

Reading the list of emails and the message content

Here, we have created function email_list() which reads the list of email and returns the names and emails from the file. And the next function message_content() reads the content of the message. Here we can see, instead of reading and returning the contents, we have used Template which returns an object instead of a string.

Now going into the main part of the program, we need to setup a SMTP client in order to be able to send emails from our local machine.

Setting up SMTP

Here, we have read the receiver list and the message body. Then we have setup the SMTP to be able to send the messages. The smtp.gmail.com with port number 465 is default provided by Gmail. This can be different for different service providers.

Sending emails to all receivers

Now, we need to send the email to each of the receivers. For each of the receivers, we have created an empty message. Then we need to add different parameters in our message including Subject, From, To, etc. Then we have replaced the name of the receiver from ${PERSON_NAME} mentioned in the ‘message.txt’ file. Then we have added the contents of the message to the message. And using the SMTP connection we created earlier, we have sent the message. And after sending emails to all the receivers, the SMTP connection is closed and we have successfully sent emails to all the receivers.

Adding more flavors

Customizing the mail

Instead of sending plain text, we can add attachments, customize the contents of the email, etc. To customize the contents of the mail, we can use HTML and we need to mention the type of the text as HTML. Now we add an image to the mail as an attachment. To send the image, first we open the image ‘ok.jpg’ in binary. Then we set the name of the image to be Attachment_image.jpg. If you have an image of extension that is not supported by default, you need to mention it as well. Then we attach the image and send the email.

What’s more?

Apart from this, we can extend our program in multiple ways. We can change it to read the list of the receiver from a CSV file. Also, we can send different attachments to different receivers. Also, we can send the certificates, assignments, or anything each different for each of the receivers.

If you have anything new that could be added, I would love to hear it.

Thank you!

You may also like...