5

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Prateek Narendra
  • 1,837
  • 5
  • 38
  • 67

3 Answers3

3

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")
Sanket
  • 119
  • 1
  • 6
  • 15
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/350567) 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. – iBug Jan 10 '18 at 04:11
  • 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 access – Julanu Feb 20 '19 at 07:28
  • @Jewlanu were you able to access sub-sub folder? – misguided Nov 14 '20 at 03:23
2

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

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

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
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.