【问题标题】:Python script to send email to multiple recipients with different attachments用于向具有不同附件的多个收件人发送电子邮件的 Python 脚本
【发布时间】:2018-07-16 21:19:15
【问题描述】:

我有一个 python 程序,可以通过多个附件向多个收件人发送电子邮件(它将所有 pdf 文件放在一个文件夹中并发送电子邮件)。现在我想做这个

我的文件夹包含

file1.pdf file2.pdf file3.pdf file4.pdf file5.pdf file6.pdf.....

我有一个文本文件,其中包含名称、电子邮件 ID 和要附加的文件列表

recipient1 recipient1@gmail.com file1.pdf file2.pdf file3.pdf file4.pdf

recipient2 recipient2@gmail.com file2.pdf file3.pdf

recipient3 recipient3@gmail.com file1.pdf file2.pdf

   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,我可以使用类似的方式读取要附加到每个收件人的文件

【问题讨论】:

    标签: python email pdf


    【解决方案1】:

    只要人名或 PDF 文件名中没有空格,您就可以使用相同的代码来获取剩余信息。试试这个:

    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 文件的列表。列表中的索引与emailsnames 列表中的相应索引相匹配。请注意使用切片符号 [2:] 在一个表达式中获取所有 PDF。

    拨打str.split() 三次似乎很麻烦。我们调用一次并保存结果如何?

    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:])
    

    【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2015-08-29
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    相关资源
    最近更新 更多