Prateek Narendra
Prateek Narendra

Reputation: 1937

How to access a subfolder in Outlook inbox in Python

I have created a rule in Outlook to move all incoming messages from a particular sender to a subfolder in my Inbox.Like -

Inbox
- Subfolder

I wrote a piece of code

import win32com.client

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

inbox = outlook.GetDefaultFolder(6) #6 = Inbox (without mails from the subfolder)
messages = inbox.Items
message = messages.GetLast()
body_content = message.body 
print body_content #Sometimes has parsing error due to different encoding format

How can I

1) Read the mails in this particular folder inside Inbox

2) Take care of error like UnicodeEncodeError: 'charmap' codec can't encode - character maps to

print (u'\2109') issues this error too.

Upvotes: 6

Views: 21572

Answers (3)

Suraj Kumar Nanda
Suraj Kumar Nanda

Reputation: 59

outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")

inbox = mapi.GetDefaultFolder(6).Folders["SubFolder"]
mails = inbox.Items

The above method will also work.

Upvotes: 0

Sanket
Sanket

Reputation: 129

outlook.GetDefaultFolder(6) is "Inbox" position by default. You need to traverse the list of folders in it, so try this

inbox = outlook.GetDefaultFolder(6).Folders.Item("Your_Folder_Name")

Upvotes: 4

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

u'\2109' looks a lot like UTF-8 encoding.

So print(body_content.encode("utf-8")) will do the trick.

Upvotes: 2

Related Questions