TOPIC: Python Mini Project 01 - Mail Merge Program
Mail Merge
Mail merge is a process used to create multiple personalized documents, such as letters, emails, or
labels, from a template and a data source containing variable information.
Initially, we
create a document template using software like Microsoft Word or Google Docs. This template contains
the fixed text or content that remains the same across all the documents. However, certain parts of
the document, such as recipient names, addresses, or other variable information, are left blank or
marked as placeholders. In the same manner, we are going to use Python Program to merge two files so
that we can generate our own mail merge functionalities. So, this blog will help us how to create a
mail merge program using python.
Creation of Files
First of all, we need to create at least two files so that we can merge them together. Let us say,
we already created a file with the filename Students.txt which includes
all the names of the students of a school. Also, we created a file with the filename Data.txt which includes all the details to be sent for a notice to the
students.
Now, we are required to send the same notice to all the students. In order to do so, we open the
Students file with the open() function opening it in read mode, and assigns the file Objects(file
contents)
to a variable. We can give the variable name as we want.
with open("Students.txt", "r") as variable_name
Then, we will open the Info file, as same as above but inside the above function
with open("Info.txt", "r") as variable_name
Then, we will read the file contents using read() function and store it in a new variable. And we use a
for loop to get all the students from the file and declare a variable to generate a message with the
information. We use the string method to join the information and the message. It will automatically
create a text-content which will be saved to the said variable. Then, we open the file which contains
the name of the students and use the strip method to strip the name of the students and get only the
first set of strings and use them as the filename for sending the mail. By doing so, we will be able to
get the mail or information stored to a new file with the filename as the name of the student. After
that, we write the message by using the write() function and the information to the file. In this way,
we can send the file-contents to many students as we want. Code as discussed in the video:
# Mail Merge Program
with open("Users.txt", "r") as Users:
with open("Info.txt", "r") as Body:
info = Body.read()
for user in Users:
msg = "Greetings " + user + " " + info # Greetings Tomba Hello!!
with open(user.strip() + ".txt", "w") as Mail:
Mail.write(msg)
You can copy and run this code