为什么 Exchangelib 不能在 pythonanywhere 上运行?

发布于 2025-01-09 04:33:33 字数 10349 浏览 2 评论 0原文

我已经使用 Exchangelib 包很多年了,但它似乎不适用于 pythonanywhere。我在本地 Mac 上运行相同的脚本(可以预见,运行良好且正常),但在 PA 上,标准输出跟踪输出显示我的信用是错误的,尽管它们绝对是正确的。注意:

  1. 我在 pythonanywhere 上的正确环境中运行了脚本,
  2. 我在 pythonanywhere 上有一个付费帐户,因此 AFAIK 不应将任何 IP/域列入黑名单。
  3. 附件是在我的 Mac 上成功运行测试代码的标准输出的屏幕截图。
  4. 我就这个问题联系了 pythonanywhere,但他们坚持认为我的信用肯定是错误的。
  5. 这是测试代码:
    from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, Configuration, FaultTolerance
    import logging
    logging.basicConfig()
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)

    def connect_to_EWS(_USERNAME_, _PASS_, _PRIMARY_SMTP_ADDRESS_):

        creds = Credentials(_USERNAME_,_PASS_)

        config = Configuration(credentials=creds, server='outlook.office365.com/EWS/Exchange.asmx')
    
        return Account(
        primary_smtp_address=_PRIMARY_SMTP_ADDRESS_,
        autodiscover=False, 
        config = config,
        access_type=DELEGATE
        )
    
    account = connect_to_EWS("username", "pswd", "pri_smtp_address")

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

  1. 最后,这是 pythonanywhere 上 stdout 的跟踪输出:

    (Ankwil_Beta_Env) 16:58 ~/ankwilbeta001 (main)$ python exchangelib_patrick.py
DEBUG:exchangelib.protocol:Waiting for _protocol_cache_lock
DEBUG:exchangelib.protocol:Protocol __call__ cache miss. Adding key '('https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx', Credentials('[email protected]', '********'))'
DEBUG:exchangelib.transport:Requesting b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><s:Header><t:RequestServerVersion Version="Exchange2019"/></s:Header><s:Body><m:ResolveNames ReturnFullContactData="false"><m:UnresolvedEntry>[email protected]</m:UnresolvedEntry></m:ResolveNames></s:Body></s:Envelope>' from https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx
DEBUG:exchangelib.transport:Trying to get service auth type for https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): outlook.office365.com:443
DEBUG:urllib3.connectionpool:https://outlook.office365.com:443 "POST /EWS/Exchange.asmx/EWS/Exchange.asmx HTTP/1.1" 401 0
DEBUG:exchangelib.transport:Request headers: {'User-Agent': 'exchangelib/4.6.2 (python-requests/2.26.0)', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '463'}
DEBUG:exchangelib.transport:Response headers: {'Server': 'Microsoft-IIS/10.0', 'request-id': 'c79f0912-fa68-5081-e0f1-ae8954057853', 'Alt-Svc': 'h3=":443",h3-29=":443"', 'X-FirstHopCafeEFZ': 'MNZ', 'X-Powered-By': 'ASP.NET', 'X-FEServer': 'BL1PR13CA0190', 'WWW-Authenticate': 'Basic Realm=""', 'Date': 'Mon, 21 Feb 2022 16:58:32 GMT', 'Content-Length': '0'}
DEBUG:exchangelib.transport:realm: 
DEBUG:exchangelib.transport:Auth type is basic
DEBUG:exchangelib.version:Asking server for version info using API version Exchange2019
DEBUG:exchangelib.services.common:Processing chunk 1 containing 1 items
DEBUG:exchangelib.services.common:Calling service ResolveNames
DEBUG:exchangelib.services.common:Trying API version Exchange2019
DEBUG:exchangelib.protocol:Server outlook.office365.com: Increasing session pool size from 0 to 1
DEBUG:exchangelib.protocol:Server outlook.office365.com: Created session 26528
DEBUG:exchangelib.protocol:Server outlook.office365.com: Waiting for session
DEBUG:exchangelib.protocol:Server outlook.office365.com: Got session 26528
DEBUG:exchangelib.util:Session 26528 thread 139771968923456: retry 0 timeout 120 POST'ing to https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx after 10s wait
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): outlook.office365.com:443
DEBUG:urllib3.connectionpool:https://outlook.office365.com:443 "POST /EWS/Exchange.asmx/EWS/Exchange.asmx HTTP/1.1" 401 0
DEBUG:exchangelib.util:Retry: 0
Waited: 10
Timeout: 120
Session: 26528
Thread: 139771968923456
Auth type: <requests.auth.HTTPBasicAuth object at 0x7f1f2ea15e10>
URL: https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx
HTTP adapter: <requests.adapters.HTTPAdapter object at 0x7f1f2ea15450>
Allow redirects: False
Streaming: False
Response time: 0.30712076199415606
Status code: 401
Request headers: {'User-Agent': 'exchangelib/4.6.2 (python-requests/2.26.0)', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '463', 'Authorization': 'Basic cGtzdGFjZXlAb3V0bG9vay5jb206ZDMzcHRoMG5nT3V0bG9vaw=='}
Response headers: {'Server': 'Microsoft-IIS/10.0', 'request-id': '13126a04-5ecb-9622-86b9-7ead817593b4', 'Alt-Svc': 'h3=":443",h3-29=":443"', 'X-CalculatedFETarget': 'CWLP123CU010.internal.outlook.com', 'X-BackEndHttpStatus': '401, 401', 'Set-Cookie': 'exchangecookie=c2da6958e6a342b4a11ad5adc3e5e940; expires=Tue, 21-Feb-2023 16:58:32 GMT; path=/; secure; HttpOnly', 'X-FEProxyInfo': 'CWLP123CA0222.GBRP123.PROD.OUTLOOK.COM', 'X-CalculatedBETarget': 'CWLP123MB5491.GBRP123.PROD.OUTLOOK.COM', 'X-RUM-Validated': '1', 'X-BeSku': 'WCS6', 'X-DiagInfo': 'CWLP123MB5491', 'X-BEServer': 'CWLP123MB5491', 'X-Proxy-RoutingCorrectness': '1', 'X-Proxy-BackendServerStatus': '401', 'X-FEServer': 'CWLP123CA0222, BL1PR13CA0192', 'X-FirstHopCafeEFZ': 'MNZ', 'X-Powered-By': 'ASP.NET', 'WWW-Authenticate': 'Basic Realm=""', 'Date': 'Mon, 21 Feb 2022 16:58:31 GMT', 'Content-Length': '0'}
DEBUG:exchangelib.util.xml:Request XML: b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><s:Header><t:RequestServerVersion Version="Exchange2019"/></s:Header><s:Body><m:ResolveNames ReturnFullContactData="false"><m:UnresolvedEntry>[email protected]</m:UnresolvedEntry></m:ResolveNames></s:Body></s:Envelope>'
Response XML: b''
DEBUG:exchangelib.protocol:No retry: no fail-fast policy
DEBUG:exchangelib.protocol:Server outlook.office365.com: Retiring session 26528
DEBUG:exchangelib.protocol:Server outlook.office365.com: Created session 23658
DEBUG:exchangelib.protocol:Server outlook.office365.com: Releasing session 23658
Traceback (most recent call last):
  File "exchangelib_patrick.py", line 22, in <module>
    account = connect_to_EWS("[email protected]", "<hidden>", "[email protected]")
2006/types"><s:Header><t:RequestServerVersion Version="Exchange2019"/></s:Header><s:Body><m:ResolveNames ReturnFullContactData="false"><m:
  File "exchangelib_patrick.py", line 19, in connect_to_EWS
    access_type=DELEGATE
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/account.py", line 136, in __init__
    self.version = self.protocol.version
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/protocol.py", line 470, in version
    self.config.version = Version.guess(self, api_version_hint=self._api_version_hint)
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/version.py", line 229, in guess
    list(ResolveNames(protocol=protocol).call(unresolved_entries=[name]))
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/resolve_names.py", line 52, in _ele
ms_to_objs
    for elem in elems:
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 206, in _chunked_g
et_elements
    yield from self._get_elements(payload=payload_func(chunk, **kwargs))
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 226, in _get_eleme
nts
    yield from self._response_generator(payload=payload)
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 190, in _response_
generator
    response = self._get_response_xml(payload=payload)
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 312, in _get_respo
nse_xml
    r = self._get_response(payload=payload, api_version=api_version)
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 279, in _get_respo
nse
    timeout=self.timeout or self.protocol.TIMEOUT,
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/util.py", line 877, in post_ratelimited
    protocol.retry_policy.raise_response_errors(r)  # Always raises an exception
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/protocol.py", line 689, in raise_response_er
rors
    raise UnauthorizedError('Invalid credentials for %s' % response.url)
exchangelib.errors.UnauthorizedError: Invalid credentials for https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx
DEBUG:exchangelib.protocol:Server outlook.office365.com: Closing sessions
(Ankwil_Beta_Env) 16:58 ~/ankwilbeta001 (main)$ 

I've used the exchangelib package for years, but it does not seem to work on pythonanywhere. I run the identical script on my local mac (which runs predictably well and normally) but on PA the stdout trace output says my creds are wrong, eventhough they are definitively correct. Notes:

  1. I ran the script from the proper environment on pythonanywhere
  2. I have a paid account on pythonanywhere, so no IPs/domains should be blacklisted AFAIK.
  3. Attached is a screen grab of the stdout having run the test code successfully on my mac.
  4. I contacted pythonanywhere about the issue but they insisted my creds must be wrong.
  5. Here is the test code:
    from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, Configuration, FaultTolerance
    import logging
    logging.basicConfig()
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)

    def connect_to_EWS(_USERNAME_, _PASS_, _PRIMARY_SMTP_ADDRESS_):

        creds = Credentials(_USERNAME_,_PASS_)

        config = Configuration(credentials=creds, server='outlook.office365.com/EWS/Exchange.asmx')
    
        return Account(
        primary_smtp_address=_PRIMARY_SMTP_ADDRESS_,
        autodiscover=False, 
        config = config,
        access_type=DELEGATE
        )
    
    account = connect_to_EWS("username", "pswd", "pri_smtp_address")

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

  1. And finally, here is the trace output from the stdout on pythonanywhere:

    (Ankwil_Beta_Env) 16:58 ~/ankwilbeta001 (main)$ python exchangelib_patrick.py
DEBUG:exchangelib.protocol:Waiting for _protocol_cache_lock
DEBUG:exchangelib.protocol:Protocol __call__ cache miss. Adding key '('https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx', Credentials('[email protected]', '********'))'
DEBUG:exchangelib.transport:Requesting b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><s:Header><t:RequestServerVersion Version="Exchange2019"/></s:Header><s:Body><m:ResolveNames ReturnFullContactData="false"><m:UnresolvedEntry>[email protected]</m:UnresolvedEntry></m:ResolveNames></s:Body></s:Envelope>' from https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx
DEBUG:exchangelib.transport:Trying to get service auth type for https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): outlook.office365.com:443
DEBUG:urllib3.connectionpool:https://outlook.office365.com:443 "POST /EWS/Exchange.asmx/EWS/Exchange.asmx HTTP/1.1" 401 0
DEBUG:exchangelib.transport:Request headers: {'User-Agent': 'exchangelib/4.6.2 (python-requests/2.26.0)', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '463'}
DEBUG:exchangelib.transport:Response headers: {'Server': 'Microsoft-IIS/10.0', 'request-id': 'c79f0912-fa68-5081-e0f1-ae8954057853', 'Alt-Svc': 'h3=":443",h3-29=":443"', 'X-FirstHopCafeEFZ': 'MNZ', 'X-Powered-By': 'ASP.NET', 'X-FEServer': 'BL1PR13CA0190', 'WWW-Authenticate': 'Basic Realm=""', 'Date': 'Mon, 21 Feb 2022 16:58:32 GMT', 'Content-Length': '0'}
DEBUG:exchangelib.transport:realm: 
DEBUG:exchangelib.transport:Auth type is basic
DEBUG:exchangelib.version:Asking server for version info using API version Exchange2019
DEBUG:exchangelib.services.common:Processing chunk 1 containing 1 items
DEBUG:exchangelib.services.common:Calling service ResolveNames
DEBUG:exchangelib.services.common:Trying API version Exchange2019
DEBUG:exchangelib.protocol:Server outlook.office365.com: Increasing session pool size from 0 to 1
DEBUG:exchangelib.protocol:Server outlook.office365.com: Created session 26528
DEBUG:exchangelib.protocol:Server outlook.office365.com: Waiting for session
DEBUG:exchangelib.protocol:Server outlook.office365.com: Got session 26528
DEBUG:exchangelib.util:Session 26528 thread 139771968923456: retry 0 timeout 120 POST'ing to https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx after 10s wait
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): outlook.office365.com:443
DEBUG:urllib3.connectionpool:https://outlook.office365.com:443 "POST /EWS/Exchange.asmx/EWS/Exchange.asmx HTTP/1.1" 401 0
DEBUG:exchangelib.util:Retry: 0
Waited: 10
Timeout: 120
Session: 26528
Thread: 139771968923456
Auth type: <requests.auth.HTTPBasicAuth object at 0x7f1f2ea15e10>
URL: https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx
HTTP adapter: <requests.adapters.HTTPAdapter object at 0x7f1f2ea15450>
Allow redirects: False
Streaming: False
Response time: 0.30712076199415606
Status code: 401
Request headers: {'User-Agent': 'exchangelib/4.6.2 (python-requests/2.26.0)', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '463', 'Authorization': 'Basic cGtzdGFjZXlAb3V0bG9vay5jb206ZDMzcHRoMG5nT3V0bG9vaw=='}
Response headers: {'Server': 'Microsoft-IIS/10.0', 'request-id': '13126a04-5ecb-9622-86b9-7ead817593b4', 'Alt-Svc': 'h3=":443",h3-29=":443"', 'X-CalculatedFETarget': 'CWLP123CU010.internal.outlook.com', 'X-BackEndHttpStatus': '401, 401', 'Set-Cookie': 'exchangecookie=c2da6958e6a342b4a11ad5adc3e5e940; expires=Tue, 21-Feb-2023 16:58:32 GMT; path=/; secure; HttpOnly', 'X-FEProxyInfo': 'CWLP123CA0222.GBRP123.PROD.OUTLOOK.COM', 'X-CalculatedBETarget': 'CWLP123MB5491.GBRP123.PROD.OUTLOOK.COM', 'X-RUM-Validated': '1', 'X-BeSku': 'WCS6', 'X-DiagInfo': 'CWLP123MB5491', 'X-BEServer': 'CWLP123MB5491', 'X-Proxy-RoutingCorrectness': '1', 'X-Proxy-BackendServerStatus': '401', 'X-FEServer': 'CWLP123CA0222, BL1PR13CA0192', 'X-FirstHopCafeEFZ': 'MNZ', 'X-Powered-By': 'ASP.NET', 'WWW-Authenticate': 'Basic Realm=""', 'Date': 'Mon, 21 Feb 2022 16:58:31 GMT', 'Content-Length': '0'}
DEBUG:exchangelib.util.xml:Request XML: b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><s:Header><t:RequestServerVersion Version="Exchange2019"/></s:Header><s:Body><m:ResolveNames ReturnFullContactData="false"><m:UnresolvedEntry>[email protected]</m:UnresolvedEntry></m:ResolveNames></s:Body></s:Envelope>'
Response XML: b''
DEBUG:exchangelib.protocol:No retry: no fail-fast policy
DEBUG:exchangelib.protocol:Server outlook.office365.com: Retiring session 26528
DEBUG:exchangelib.protocol:Server outlook.office365.com: Created session 23658
DEBUG:exchangelib.protocol:Server outlook.office365.com: Releasing session 23658
Traceback (most recent call last):
  File "exchangelib_patrick.py", line 22, in <module>
    account = connect_to_EWS("[email protected]", "<hidden>", "[email protected]")
2006/types"><s:Header><t:RequestServerVersion Version="Exchange2019"/></s:Header><s:Body><m:ResolveNames ReturnFullContactData="false"><m:
  File "exchangelib_patrick.py", line 19, in connect_to_EWS
    access_type=DELEGATE
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/account.py", line 136, in __init__
    self.version = self.protocol.version
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/protocol.py", line 470, in version
    self.config.version = Version.guess(self, api_version_hint=self._api_version_hint)
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/version.py", line 229, in guess
    list(ResolveNames(protocol=protocol).call(unresolved_entries=[name]))
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/resolve_names.py", line 52, in _ele
ms_to_objs
    for elem in elems:
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 206, in _chunked_g
et_elements
    yield from self._get_elements(payload=payload_func(chunk, **kwargs))
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 226, in _get_eleme
nts
    yield from self._response_generator(payload=payload)
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 190, in _response_
generator
    response = self._get_response_xml(payload=payload)
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 312, in _get_respo
nse_xml
    r = self._get_response(payload=payload, api_version=api_version)
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/services/common.py", line 279, in _get_respo
nse
    timeout=self.timeout or self.protocol.TIMEOUT,
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/util.py", line 877, in post_ratelimited
    protocol.retry_policy.raise_response_errors(r)  # Always raises an exception
  File "/home/ankwilitas/.virtualenvs/Ankwil_Beta_Env/lib/python3.7/site-packages/exchangelib/protocol.py", line 689, in raise_response_er
rors
    raise UnauthorizedError('Invalid credentials for %s' % response.url)
exchangelib.errors.UnauthorizedError: Invalid credentials for https://outlook.office365.com/EWS/Exchange.asmx/EWS/Exchange.asmx
DEBUG:exchangelib.protocol:Server outlook.office365.com: Closing sessions
(Ankwil_Beta_Env) 16:58 ~/ankwilbeta001 (main)$ 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文