简体   繁体   中英

How to get highlighted (selected) mail from outlook using Python?

I can not understand how to parse highlighted (selected) mail from outlook using Python?

I have this code, but it works with last mail.

import win32com.client

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

inbox = outlook.GetDefaultFolder(6)

messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print (body_content)

Need to parse sender email address of highlighted mail?

Should be

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application")
messages = outlook.ActiveExplorer().Selection
message = messages(1)

try:
    if message.SenderEmailType == "EX":
        print("EX: ", message.Sender.GetExchangeUser().PrimarySmtpAddress)
    else:
        if message.SenderEmailType == "SMTP":
            print("SMTP: ", message.SenderEmailAddress)
except Exception as e:
    print(e)

Use Application.ActiveExplorer.Selection.Item(1) to retrieve the currently selected message. Your code retrieves the last email in the Inbox - whatever "last" is, since you never explicitly sort the items collection. Most likely you will end up with the oldest email in the Inbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM