0

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 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

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

Reems
  • 7
  • 1
  • 5

1 Answers1

0

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:])
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Thank you so much Rob. That worked so well. I am now working to try to get to attach the pdf to the email. – Reems Feb 06 '18 at 18:32
  • Good luck! This might help: https://stackoverflow.com/questions/3362600/how-to-send-email-attachments – Robᵩ Feb 06 '18 at 18:34