Automate email sending with an attached file on Python

Tien Nguyen
3 min readDec 8, 2020

Imaging that you have a task to send by email the sales report to each sales representative per week and you have approximately 40 sales representatives across the world. Are you already stressed out by spending hours on sending those emails? With the basic skills on Python, this article will show you how to automate that task and you have more time to enjoy a cup of coffee in the office!

Source:https://www.thenormandy.com/in-mail/

Step1: Import all essential packages

The basic modules we should use here are pandas, smtplib, ssl and email. The module smtplib allows to send email to any Internet machine with an SMTP (Simple Mail Transfer Protocol) or ESMT listener daemon. The email package supports to create any text structure from scratch or parse the plain message to upload into the prepare emails. All modules in this article are built-in modules, hence, we do not need to install any of them in your computer’s environment.

Step2: Create the SMTP Object to connect to your email server

Once we import those modules, we can start to create SMTP object which will be used to send an email. Do not forget to enter your email and password in order for the object to connect to your email server later. We use the outlook as the mail host server in this article. You can enter IP address of the host or the domain name instead. The port argument is 587 where SMTP server is listening.

Step3: Get a list of emails and a sales report

The sales report is stored under an excel file and it shows all products with responsible sales representatives. Hence, we need to modify the sales report for each sales representative. Moreover, the information of emails appear many times, which needs to clear up to avoid sending a same emails to the same person for many times.

Step4: Create modified sales reports and send to each sales representative

Now we have a list of all receivers, it is time for looping those names. The basic structure of the attached code lines is

  • Create the body text which is similar to all receivers
  • Generate the modified sales report which contains relevant products for different sales representative
  • Save the modified sales report into an excel format and re-read it as an attached file for the email
  • Send the email with an attached file and receive a message about sending status

Do not forget to close the connection which we already built with an email server! That’s all. You can save your code and run it at any time if you have the same task. Definitely, it saves a lot of time and effort for you!

--

--

Tien Nguyen

Senior Analyst with a strong passion for data and business strategy. "Learner/Sharer/Improver/Doer"