Python script to send email to multiple recipients with different attachments
我有一个 python 程序,可以通过多个附件向多个收件人发送电子邮件(它获取文件夹中的所有 pdf 文件并发送电子邮件)。现在我想做这个
我的文件夹包含
file1.pdf file2.pdf file3.pdf file4.pdf file5.pdf file6.pdf.....
我有一个文本文件,其中包含名称、电子邮件 ID 和要附加的文件列表
recipient1 file1.pdf file2.pdf file3.pdf file4.pdf
recipient2 file2.pdf file3.pdf
recipient3 file1.pdf file2.pdf
1 2 3 4 5 6 7 8 |
def get_contacts (filename ): names = [ ] emails = [ ] with open (filename , mode = 'r' , encoding = 'utf-8' ) as contacts_file: for a_contact in contacts_file: names. append (a_contact. split ( ) [ 0 ] ) emails. append (a_contact. split ( ) [ 1 ] ) return names , emails |
我正在使用上面的代码读取一个文本文件并获取收件人的姓名和电子邮件ID,我可以使用类似的方式来读取要附加到每个收件人的文件
您可以使用相同的代码来获取其余信息,只要人名或 PDF 文件名中没有空格即可。试试这个:
1 2 3 4 5 6 7 |
pdfs = [ ] ... for a_contact in contacts_file: names. append (a_contact. split ( ) [ 0 ] ) emails. append (a_contact. split ( ) [ 1 ] ) pdfs. append (a_contact. split ( ) [ 2: ] ) return names , emails , pdfs |
这将创建一个 PDF 文件的列表。列表中的索引与 emails 和 names 列表中的相应索引匹配。请注意使用切片表示法 [2:] 在一个表达式中获取所有 PDF。
调用 str.split() 三次似乎很麻烦。我们调用一次并保存结果怎么样?
1 2 3 4 5 |
for a_contact in contacts_file: a_contact_list = a_contact. split ( ) names. append (a_contact_list [ 0 ] ) emails. append (a_contact_list [ 1 ] ) pdfs. append (a_contact_list [ 2: ] ) |
- 非常感谢罗布。那效果很好。我现在正在努力尝试将 pdf 附加到电子邮件中。
- 祝你好运!这可能会有所帮助:stackoverflow.com/questions/3362600/...
本文由 华域联盟 原创撰写:华域联盟 » 用于向具有不同附件的多个收件人发送电子邮件的 Python 脚本
转载请保留出处和原文链接:https://www.cnhackhy.com/158228.htm