DyingInCS
DyingInCS

Reputation: 51

How could I find the Sender Department in Microsoft Outlook using win32com in Python?

I am programming a script to return each person - along with their department - that was a part of a thread in my Junk folder. As of now I have managed to correctly return their names, however despite trying multiple different methods, I have been unable to access the Departments property.

Here is an example of what I am currently working with:

import win32com.client  

output_dir = Path.cwd() / "Output"
output_dir.mkdir(parents=True, exist_ok=True)


outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

gal = outlook.Session.GetGlobalAddressList()
entries = gal.AddressEntries

inbox = outlook.GetDefaultFolder(23)

messages = inbox.Items
num = 0

for message in messages:
    author = message.SenderName
    
    recipient = outlook.CreateRecipient(f"{message.SenderEmailAddress.partition('-')[2]}@placeholder.com")
    recipient.Resolve()

    target_folder = output_dir / str(num)
    target_folder.mkdir(parents=True, exist_ok=True)

    Path(target_folder / "EMAIL_author.txt").write_text(str(message.SenderName))
    Path(target_folder / "EMAIL_YEAR.txt").write_text(str(recipient.AddressEntry.GetExchangeUser().GetExchangeUserManager()))

    num += 1

Currently working in Python 3.10.8

Any help is appreciated.

Upvotes: 0

Views: 189

Answers (1)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66235

There is no reason to use CreateRecipient / Recipient.Resolve - MailItem.Sender property already exposes the AddressEntry object for the sender. Once you get ExchangeUser object from AddressEntry.GetExchangeUser() (check for null), just use the ExchangeUser.Department property.

Upvotes: 1

Related Questions