使用 python api O365 接收电子邮件

Ehi*_*ayi 3 python email-attachments python-3.x office365

我刚刚开始使用Python,我正在尝试完成一项手动任务,我听说使用Python 完成它更简单。我的公司使用 Office 365 处理电子邮件,我想检索电子邮件附件并将其存储在本地,以便节省时间。到目前为止,已经确定了如何发送简单的电子邮件,调用我帐户中文件夹的名称,但我不知道如何阅读任何特定的电子邮件。

我的想法有点像这样

from O365 import Account, message,mailbox

credentials =  ('username', 'given password')

account = Account(credentials)
mailbox = account.mailbox()
mail_folder = mailbox.inbox_folder()
mail_folder = mailbox.get_folder(folder_name='Inbox')
print(mail_folder)
#_init__(*,parent= Inbox, con=None,**kwargs)
Message_body = message.body()
message.get_subject('email subject here!')
print(Message.body)
Run Code Online (Sandbox Code Playgroud)

现在我迷失了并尝试 O365 文档页面中的任何内容,但消息模块根据我的使用方式没有属性主题。任何指导将不胜感激

Chr*_*lor 5

从你的例子来看 - 不清楚你是否通过了身份验证......

如果是,那么您将能够列出邮箱文件夹。在下面的情况下 - 您可以访问收件箱,然后列出子文件夹:

from O365 import Account, Connection,  MSGraphProtocol, Message, MailBox, oauth_authentication_flow

scopes=['basic', 'message_all']
credentials=(<secret>, <another secret>)
account = Account(credentials = credentials)

if not account.is_authenticated:  # will check if there is a token and has not expired
    account.authenticate(scopes=scopes)

account.connection.refresh_token()mailbox = account.mailbox()
inbox = mailbox.get_folder(folder_name='Inbox')
child_folders = inbox.get_folders(25)
for folder in child_folders:
    print(folder.name, folder.parent_id)
Run Code Online (Sandbox Code Playgroud)

这部分将允许您列出文件夹(以及消息)。

如果我看一下你的代码 - 看起来你好像想同时做这两件事?

尝试执行以下操作来掌握在收件箱中分页的窍门:

for message in inbox.get_messages(5):
    if message.subject == 'test':
        print(message.body)
Run Code Online (Sandbox Code Playgroud)

请注意,我正在循环浏览收件箱中的前 5 条消息,查找主题为“test”的消息。如果它找到消息 - 那么它会打印正文。

希望这能带来一点启发。