1

I have the below code that downloads he attachments from the outlook. But I'm having two problems. 1. Attachment wont be downloaded if there is already a file with the same name in the folder. I want it to be replaced with the new file (file names are same but with updated data). 2. The code is downloading all the images that it finds in the email. Its not a big problem, I can write a extra small code for it but I wanted to learn if its possible to exclude images inside the code I have.

import os
import win32com.client

path = r"C://Users//greencolor//Desktop//Autoreport//Load_attachments//"
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items


def save_attachments(subject_prefix): # changed parameter name
    messages.Sort("[ReceivedTime]", True)  # sort by received date: newest to oldest
    for message in messages:
        if message.Subject.startswith(subject_prefix): # changed test
            print("saving attachments for:", message.Subject)
            for attachment in message.Attachments:
                print(attachment.FileName)
                attachment.SaveAsFile(os.path.join(path, str(attachment.FileName)))  # changed to file-name
            return

save_attachments('PB Report North Cluster - ' )
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Greencolor
  • 501
  • 1
  • 5
  • 16

1 Answers1

0

Iterating through all messages in a folder and checking the Subject line is not really a good idea. Instead, you need to find only items that correspond to your conditions (with a particular subject line and attachments) and only then iterate over found items to save attachments. The Find/FindNext or Restrict methods can help you with that task in Outlook. Read more about them in the following articles:

You may find keyword in the subject line using the following search criteria:

filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " LIKE '%" & wordsInSubject & " %'"

And the following search criteria is used to find items with attachments only:

filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:hasattachment" & Chr(34) & "=True"

You can combine these two search criteria using the AND operator in the string (like you do in SQL).

Finally, you may check whether a file already exists with the same on the disk using the file system object, see VBA check if file exists for more information.

  1. The code is downloading all the images that it finds in the email. Its not a big problem, I can write a extra small code for it but I wanted to learn if its possible to exclude images inside the code I have.

You can detect embedded images by checking for the cid:imageName substring in the message body. See Embedding image in email with VBA for more information.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45