0
votes

I have a python program that sends email to muliple recipients with multiple attachments(it takes all the pdf files in a folder and sends the email). Now I want to do this

my folder contains

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

I have a text file that would contain the name, emailid and list of files to be attached

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

   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

I am using the above code to read a text file and get the name and email id of the recipient, Can I use a similar way to read the files to be attached to the each recipient

1

1 Answers

0
votes

You can use the same code to get the remaining information, as long as there are no spaces in the peoples names or the PDF file names. Try this:

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

This will create a list-of-lists of PDF files. The index into the list matches the corresponding index into the emails and names lists. Note the use of slice notation [2:] to grab all of the PDFs in one expression.

Calling str.split() three times seems messy. How about we call it once and save the result?

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