NonSleeper
NonSleeper

Reputation: 851

Retrieve Outlook internal emails by email address using Python pywin32

I'm trying to use Python to access Outlook mail.

Code I learnt from several sources:

# Import packages
import os
import win32com.client
from datetime import datetime, timedelta

# Initiate an Outlook session
outlook = win32com.client.Dispatch('Outlook.Application')
mapi = outlook.GetNamespace("MAPI")

# Specify the folder
inbox = mapi.GetDefaultFolder(6)
InboxMessages = inbox.Items

# Apply filters
ReceivedDateTime = datetime.now() - timedelta(days=7)
InboxMessages = [message for message in InboxMessages if message.ReceivedTime.timestamp() >= ReceivedDateTime.timestamp()]
InboxMessages = [message for message in InboxMessages if message.SenderEmailAddress.__contains__('mycompany.com')]

I have a condition that filters sender email addresses.

If I specify email addresses from my company, it only returns a part of the emails in my Inbox.

It appears that emails not being returned are those with a label we use to assign the emails. They may be important or not so, from Casual, Hangout, Urgent, etc. Regardless, if assigned a label, it's not returned.

All company emails without labels are returned. Again, it doesn't matter who sent those mails or how important they are.
Also, there doesn't seem such a problem with emails from external sources.

What could potentially lead to this result, like a security encryption?

Upvotes: 0

Views: 501

Answers (1)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66286

Firstly, never loop through all messages in a folder, you'd never create a SELECT SQL query without a WHERE clause, would you? Use Items.Restrict or Items.Find/FindNext - let the store provider do the job.

Secondly, internal messages sent between two mailboxes have "EX" type sender address (MailItem.SenderEmailType == "EX"), not "SMTP". Create a restriction on the PidTagSenderSmtpAddress property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x5D01001F") - take a look a message with OutlookSpy (I am its author, click IMessage button).

Your query would be like the following (it specifies PR_MESSAGE_DELIVERY_TIME, PidTagSenderSmtpAddress, and PR_SENDER_EMAIL_ADDRESS DASL property names):

@SQL="http://schemas.microsoft.com/mapi/proptag/0x0E060040" > '2022-07-19' AND ("http://schemas.microsoft.com/mapi/proptag/0x5D01001F" LIKE '%@mycompany' OR "http://schemas.microsoft.com/mapi/proptag/0x0C1F001F" LIKE '%@mycompany.com')

Upvotes: 1

Related Questions