2

At the end of some code I will have a list like this and each time I run it there will be a different number of elements in the list (up to 8 elements):

['9/Ma7_8.pdf', '8/Ma5_6.pdf', '9/Ma5_1.pdf']

I need to be able to create an email which adds as many attachments as there are elements in the list and each attachment in the folder I am adding is called the same as the items in the list. So for the list above, I will need to add three attachments called:

9/Ma7_8.pdf
8/Ma5_6.pdf
9/Ma5_1.pdf

I am using the following the do the email:

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = ''
mail.CC = ''
mail.Subject = '...'
mail.Body = contents

My question is how do I write the code to add attachments?

If I was doing it manually then:

mail.Attachments.Add('9/Ma7_8.pdf')
mail.Attachments.Add('8/Ma5_6.pdf')
mail.Attachments.Add('9/Ma5_1.pdf')
Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67
Loopy1687
  • 21
  • 1
  • 3

1 Answers1

4

Loop over the list and attach every item:

# attachments is your list of strings
for attachment in attachments:
    mail.Attachments.Add(attachment)
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Olaf
  • 586
  • 5
  • 18
  • This thread was recommended by the former editor of the post: https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory – bad_coder May 17 '20 at 00:18