Python for everything!
Experience comes from facing challenges, I had encountered a challenge with the repeated task of sending personalized email messages with an attachment to multiple email addresses.
Trust me, this was very frustrating, so I thought to myself how would I use my coding skills to solve the challenge of carrying out a repeated task, to be more vivid on the task at hand, just imagine.
Having to generate personalized email messages for recipients of about 100 to 1000 people and you need to source specific data from a CSV or TEXT file, you have to be extremely patient and sturdy to achieve this task using repetition.
I usually say Python is for everything, so I began to research on how to solve the challenge using my coding skills with python programming language behold, I landed on several python modules for sending email messages, some modules for sending emails are:
1. Emails
2. Envelopes
3. Yagmail
4. Flanker
I drew up a plan and put all the coding parameters I needed in perspective also I used the Yagmail module because it is an API designed specifically for Gmail.
Firstly, I needed to be able to read the files off of the CSV file with the data of emails, names, age, and any other specific data you wish to pull off the CSV file, you can also use a TEXT file as well.
I thought of all the modules I will require for this project and they are:
CSV: This is a built-in module used to read data from CSV files.
import CSV
Yagmail: is a GMAIL/SMTP client that aims to make it as simple as possible to send emails.
Challenges encountered
1. Python has exception handling capabilities, be sure to create an exception to handle IndexError when looping through your CSV/TEXT file to collect data to be formatted on the message body or use a break statement to break out of the loop otherwise you get an index error
2. You can use with open to read() CSV/TEXT files, this closes() the file automatically after opening it, as well as open multiple files in one line of code.
3. Ensure your email password is not part of your code, you can use an input statement to collect passwords from users.
4. Ensure you set your Gmail account security option to allow other applications to access your email else, you won’t be able to log in.
Now let’s take a look at our code
First thing is to ensure that the module you will need for this project is installed on your Python then import the modules in the Python script.
Yagmail – pip install yagmail
import yagmail
import CSV
Create a variable for the attachment file, remember the file name should be enclosed in quotes, now create a variable password to collect the email password.
filename = "gbadamosi idris CV passport.pdf"
password = str(input("Enter your password: "))
Create exception to handle index error, create a counter while looping through the data in your text/csv file, use the with open to read multiple text files, in the code below text files have been created with specific data otherwise you can use a csv file with the header identifiers for each field you need to loop through.
Using readline() and readlines() you can read the line or lines of text in a text file or a .reader() method to read the data from a csv file.
The following files are collected from the text file and append to the message body using format (f) and place holders ({});
Pupils_names, email_addresses, reg_no, and classes
try:
i = -1
while True:
i = i + 1
with open("Names of pupils-good.txt", "r") as file_1, open("email adds.txt", "r") as file_2, open("reg_no.txt", "r") as file_3, open("class.txt", "r") as file_4, open("email_adds.csv") as file:
pupils_names = file_1.readlines()
email_addresses = ["idriskadiri_2000@yahoo.com", "jubrilzainab25@gmail.com"]
reg_no = file_3.readlines()
classes = file_4.readlines()
reader = csv.reader(file)
next(reader) # Skip header row
Using the counter, we will loop through the list of data in the variables listed above and save them into other variables this is to ensure that each looping is done sequentially and the emails are sent one after the other.
Also, ensure that the data you have has been cleaned and each successive row has data that corresponds otherwise a personalized email will be sent to another’s email. Hence I advise testing to know the numbers of data in each text or CSV file using len() built-in function.
full_name = pupils_names[i] admission_no = reg_no[i] email = email_addresses[i] classes_1 = classes[i]
Now, let’s format the body of the message, using place holders to enter the full names and admission numbers in the message body. It might be important to use the .strip() method to remove excess space from a text/CSV file.
news_letter = f'''
Dear Parents/Guardian
Compliments of the season, wishing you a Merry Christmas and a Happy New Year.
Kindly find attached “End of Term News Letter” for 2020/2021 academic session.
Also, find the embed link for the bill due for the Second Quarter of 2020/2021 on behalf of {full_name.strip()} with admission ID:{admission_no.strip()}.
{"-" + classes_1.strip()}.
For further inquiries on the invoice attached, as well as clarification on payment process and acknowledgments, please contact the admin.
Thank you.'''
Yag mail secure mail transfer protocol SMTP is a magic wrapper around the smtplibs (SMTP libraries) found in the emails module, it allows email messages to be sent, it collects your email and password.
Note: for security do not save your password as part of your code.
yag = yagmail.SMTP("idriskadiri2000@gmail.com", password)
yag.send(to=email, subject="End of Term News Letter", contents=news_letter, attachments=filename,)
except IndexError:
pass
Credits to @google search engine, @stackoverflow, @pypi documentation