How to access a subfolder in Outlook inbox in Python
Asked Answered
D

3

6

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.

Damn answered 10/1, 2017 at 7:21 Comment(4)
have you tried body_content.encode('cp1252') ?Snowshoe
@Jean-FrançoisFabre - print (u'\2109').encode('cp1252') - same errorDamn
try utf-8 then.Snowshoe
@Jean-FrançoisFabre - utf-8 worked. Thanks.. I tried ASCII and had given up :PDamn
M
4

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")
Minnaminnaminnie answered 10/1, 2018 at 3:40 Comment(3)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.Whoopee
Hey there! Do you know if it's possible to access a subfolder of a subfolder? In the list of folders in the mailbox I have a folder and under that I have another folder that I can't accessLiquefy
@Jewlanu were you able to access sub-sub folder?Razzledazzle
S
2

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

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

Shivaree answered 10/1, 2017 at 8:53 Comment(0)
M
0
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.

Mu answered 30/3, 2022 at 4:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.