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