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 [email protected] file1.pdf file2.pdf file3.pdf file4.pdf

recipient2 [email protected] file2.pdf file3.pdf

recipient3 [email protected] 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/…


声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。