O. Schultz
O. Schultz

Reputation: 175

Exchangelib: Moving Email from Inbox to Folder

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.

Upvotes: 5

Views: 5913

Answers (2)

Sam Marvasti
Sam Marvasti

Reputation: 118

for me what worked was

account.inbox / 'foldername'

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

Upvotes: 0

Andres
Andres

Reputation: 81

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)

Upvotes: 8

Related Questions