3

我想读出收件箱中最新的电子邮件,从中选择附件并将电子邮件移动到文件夹中。我已经有一个保存附件的代码:

from exchangelib import Credentials, Account
import os

credentials = Credentials('test.name@mail.com', 'password')
account = Account('test.name@mail.com', 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)

但我无法将电子邮件移至收件箱以外的另一个文件夹。到目前为止,我只找到了这个选项:

item.move(to_folder)

但是我不知道我应该怎么写文件夹的名字。谁能给我一个例子吗?

提前致谢。

4

1 回答 1

6

to的to_folder参数.move()必须是Folder实例,而不是文件夹名称。这是一个例子:

from exchangelib import Credentials, Account
import os


credentials = Credentials('test.name@mail.com', 'password')
account = Account('test.name@mail.com', 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)
于 2018-04-27T16:10:25.753 回答