pythonwinapioutlookpywin32office-automation

Outlook inconsistency with execution - Python


My issue is allocating emails to folders. When I allocate by subject (see code below) it works fine.

example_mail = [message for message in inbox.Items if 'example' in message.Subject]
for message in example_mail:
    if message.UnRead == True:
        message.Move(example_folder)

However, when I do the same method for allocating by email address (see code below), it will either only move a couple emails (and take extremely long for the quantity delivered) or just not seem to execute at all with no errors.

example_mail1 = [message for message in inbox.Items if 'sender@example.com' in message.SenderEmailAddress]
for message in example_mail1:
    if message.UnRead == True:
        message.Move(example_folder1)

Both methods are the same in terms of code and approach, although for some reason the outcomes are completely different. I'm using: win32, a shared email inbox (work) and a company laptop.

I have also tried the subject script on a much higher quantity to see if the problem lied within the amount of emails found when using the email address script, but even with a very small amount of emails i still get the same problem.

Any suggestions?


Solution

  • if 'sender@example.com' in message.SenderEmailAddress

    There could be multiple factors such as case sensitivity and etc. Moreover, iterating over all items in the folder is not really a good idea:

    example_mail1 = [message for message in inbox.Items if 'sender@example.com' in message.SenderEmailAddress]
    

    Plus after that code you check the UnRead property which is not efficient.

    Instead, I'd recommend using the Find/FindNext or Restrict methods of the Items class from the Outlook object model instead. So, you will get only items that correspond to your conditions.

    Read more about these methods in the following articles:

    For example, you could set up the following search criteria:

    Filter = "@SQL=" & "urn:schemas:httpmail:senderemail Like '%sender@example.com%'"