Python Program to Merge Mails

By | October 3, 2021
Python Program to Merge Mails

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 Topics to create this Program

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.

Steps:
  • 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 mail:

with open("names_file.txt",'r') as names:
    
    with open("content.txt",'r') as mail:     # open the mail content file
        #mail content
        content = mail.read() 
       
        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 = mail.read()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.

 

Vamware

Conclusion

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 contain 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:

Vamware
Author: Vinay

I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Leave a Reply

Your email address will not be published.