【问题标题】:Python reading email from outlook account using imaplib/imapclient vs exchangelib?Python 使用 imaplib/imapclient 与 exchangelib 从 Outlook 帐户读取电子邮件?
【发布时间】:2020-06-30 01:16:04
【问题描述】:

我正在设置一个脚本来读取来自 outlook.com 帐户的传入电子邮件,并且我已经使用 imaplib 测试了一些方法,但均未成功。然而,当我尝试使用 Exchangelib 时,我能够做到这一点。我不完全确定为什么 Exchangelib 有效而 imaplib 无效。我觉得我可能在这里打破了一些最佳实践,因为我不知道 Exchangelib 如何通过某种网络连接技巧连接到邮箱?

用于参考不起作用的 IMAP 代码(尽管当我尝试连接到我的个人 gmail 帐户时它起作用)

from imapclient import IMAPClient
import mailparser

with IMAPClient('outlook.office365.com', ssl=True) as server:
    server.login("username", "password")
    server.select_folder('INBOX')
    messages = server.search(['FROM', ])

    # for each unseen email in the inbox
    for uid, message_data in server.fetch(messages, 'RFC822').items():
        email_message = mailparser.parse_from_string(message_data[b'RFC822'])
        print("email ", email_message)

我收到以下错误

imapclient.exceptions.LoginError: b'LOGIN failed.'

当我使用 exchangelib 时,它可以成功运行。参考代码如下:

from exchangelib import Credentials, Account

credentials = Credentials("username", "password")
account = Account(username, credentials=credentials, autodiscover=True)

for item in account.inbox.all().order_by('-datetime_received')[:100]:
    print(item.subject, item.sender, item.datetime_received)

我无法连接 imaplib/imapclient 与 exchangelib 有什么原因吗?也许是一些我不知道的与安全相关的原因?

【问题讨论】:

  • exchangelib 可能支持 OAuth。您的管理员可能为 EWS(由 exchangelib 使用)和 IMAP(由 imaplib 使用)设置了不同的安全设置。您是否尝试过使用应用专用密码或类似密码,或使用 ADAL 库并注册 OAuth 访问权限?
  • 不,我没有尝试过应用专用密码或使用 ADAL 库。感谢您的点头 - 我将研究 IMAP 之间的 EWS。也许我可以联系管理员并获取一些信息。

标签: python imaplib exchangelib imapclient


【解决方案1】:

我认为您可能需要在使用 imapclient/imaplib 时传递完整的电子邮件 ID,而在使用 exchangelib 时只需要传递用户名。

【讨论】:

  • 感谢您的评论,我肯定会把它传递进去。这里的意思是 usernameusername@domain.com 的简写
  • 哦,好吧!尽管完全有可能,但我仍然无法想象问题出在管理员限制上。使用 imaplib,这对我有用:from imaplib import IMAP4_SSL box = IMAP4_SSL('outlook.office365.com', 993) box.login(emailID, emailPassword) 我会说你需要传入 Outlook imap 端口,但这会给你一个不同的错误。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
  • 2013-11-17
相关资源
最近更新 更多