Python Program to Merge Mails

Posted in

Python Program to Merge Mails

Vinay Khatri
Last updated on April 23, 2024

    Here in this Python tutorial, you will learn how to merge mails using Python. Here we have provided a python logical source code that can merge emails into one.

    Prerequisite Python Program to Merge Mails

    What is Mail Merging?

    When we want to send the same mail body or content to various people, so rather than writing multiple similar bodies or content for the different people, we just simply change the person's name or his address.

    Mail merge is a process in which instead of writing separate emails we list all the names we have and merge them to the main mail body.


    • Open the file which has all the names.
    • Inside it opens the file which has the content of the email.
    • Copy the mail content in a variable.
    • Now create a for loop which iterates through the names, and inside the for loop write a statement that creates a new mail file for each person.

    Python Program to Merge Mails

    with open("names_file.txt",'r') as names:
        with open("content.txt",'r') as mail:     # open the mail content file
            #mail content
            content = 
            for name in names:                  # loop over the names
                new_mail = "Hi"+name+content
                # this will create a mail file for each individual name
                with open(name.strip()+".txt",'w') as individual_mail:
                    individual_mail.write(new_mail)        #write a new mail for individual

    Behind the Code:

    Here first we open the file name_file.txt which contains all the names, then we open the file content.txt which contains the mail body or message. Then using the statement content = we copy the mail message into a variable content.

    Then we loop through the names and with each iteration of names we create a new_mail which contain the mail body and person name, and inside the loop itself we create a file with open(name.strip()+".txt",'w') by user name.


    Here in this Python tutorial, you learned how to merge mails using Python. In the above program, we use two text files, the first file contains the name and address of all the users and the second contains the message. And using the python file handling we create different message text files for every user with the same message.

    People are also reading:

    Leave a Comment on this Post