当我们想给许多人发送相同的邀请函时,邮件正文不会改变。只需要更改姓名(可能还有地址)。
邮件合并就是实现此过程的一种方法。我们无需单独编写每封邮件,而是为邮件正文创建一个模板,并生成一个姓名列表,然后将它们合并在一起以生成所有邮件。
合并邮件的源代码
# Python program to mail merger
# Names are in the file names.txt
# Body of the mail is in body.txt
# open names.txt for reading
with open("names.txt", 'r', encoding='utf-8') as names_file:
# open body.txt for reading
with open("body.txt", 'r', encoding='utf-8') as body_file:
# read entire content of the body
body = body_file.read()
# iterate over names
for name in names_file:
mail = "Hello " + name.strip() + "\n" + body
# write the mails to individual files
with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file:
mail_file.write(mail)
对于此程序,我们将所有姓名都写在“names.txt”文件中的单独行中。正文在“body.txt”文件中。
我们以读取模式打开这两个文件,并使用for 循环遍历每个姓名。将创建一个名为“ [name].txt”的新文件,其中name是该人的姓名。
我们使用strip()方法清除开头和结尾的空白字符(从文件中读取一行还会读取换行符“\n”)。最后,我们使用write()
方法将邮件内容写入此文件。
了解更多关于Python 中的文件。