📜  合并邮件的Python程序

📅  最后修改于: 2020-09-21 02:19:45             🧑  作者: Mango

在此程序中,您将学习将邮件合并为一个。

当我们希望将相同的邀请发送给许多人时,邮件的正文不会更改。仅名称(可能还有地址)需要更改。

邮件合并是执行此操作的过程。我们没有单独编写每封邮件,而是拥有邮件正文的模板和合并在一起以形成所有邮件的名称列表。

合并邮件的源代码

# 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+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文件的更多信息。