Exchangelib: Moving Email from Inbox to Folder
Asked Answered
B

2

5

I want to read out the newest E-Mail in the inbox, select the attachment out of it and move the E-Mail to a folder. I already have a code to save the attachment:

from exchangelib import Credentials, Account
import os

credentials = Credentials('[email protected]', 'password')
account = Account('[email protected]', credentials=credentials, autodiscover=True)
for item in account.inbox.all().order_by('-datetime_received')[:1]:
    for attachment in item.attachments:
        fpath = os.path.join("C:/destination/path", attachment.name)
        with open(fpath, 'wb') as f:
            f.write(attachment.content)

But I have a problem to move the E-Mail to another folder than the inbox. So far I only found this option:

item.move(to_folder)

But I don`t know how I should write in the name of the folder. Could anyone give me an example for this?

Thanks in advance.

Biller answered 27/4, 2018 at 13:2 Comment(0)
N
8

The to_folder argument to .move() must be a Folder instance, not a folder name. Here's an example:

from exchangelib import Credentials, Account
import os


credentials = Credentials('[email protected]', 'password')
account = Account('[email protected]', credentials=credentials, 
autodiscover=True)

#this will show you the account folder tree
print(account.root.tree())

#if to_folder is a sub folder of inbox
to_folder = account.inbox / 'sub_folder_name'

 #if folder is outside of inbox
 to_folder = account.root / 'folder_name'

for item in account.inbox.all().order_by('-datetime_received')[:1]:
    for attachment in item.attachments:
        fpath = os.path.join("C:/destination/path", attachment.name)
        with open(fpath, 'wb') as f:
            f.write(attachment.content)
    item.move(to_folder)
Nordau answered 27/4, 2018 at 16:10 Comment(1)
Thanks for the help so far, but now I get a CASError with "UnauthenticatedRequest", when I´m using the new code or even with the exact same code that worked on friday. Do you know, how to get rid of this problem?Biller
S
0

for me what worked was

account.inbox / 'foldername'

root would not work at all so I created a new folder under inbox

Suanne answered 14/2, 2023 at 3:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.