English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Program to Merge Emails

Complete Python Examples

In this program, you will learn to merge emails into one.

To understand this example, you should understand the followingPython Programming主题:

O

When we want to send the same invitation to many people, the email body will not change. Only the name (and possibly the address) needs to be changed.

Email merging is a process like this. We do not need to write each email separately, but we have an email body template and a name list, and we merge them together to form all emails.

Source code for merging emails
# Python program for email merging
# Names are in the file names.txt
# Email body is in body.txt
# Open names.txt for reading-8') as names_file:
   # Open body.txt for reading
   # Open body.txt for reading-8') as body_file:
   
       # Read the entire content of the body
       body = body_file.read()
       # Traverse names
       for name in names_file:
           mail = "Hello "+name+body
           # Write the email to a single file
           with open(name.strip(),+".txt",'w',encoding = 'utf-8') as mail_file:
               mail_file.write(mail)

For this program, we write all names on different lines in the file 'names.txt', and the body is located in the 'body.txt' file.

We open two files in read mode and use a for loop to iterate through each name. A new file named '[name].txt' will be created, where name is the person's name.

We use the strip() method to remove leading and trailing whitespace (when reading a line from a file, the newline character '\n' is also read). Finally, we use the write() method to write the content of the email to this file.

Learn more aboutFiles in PythonMore information.

Complete Python Examples