exchangelib https://www.e-learn.cn/tag/exchangelib zh-hans Exchangelib error in Python: www-authenticate https://www.e-learn.cn/topic/4024091 <span>Exchangelib error in Python: www-authenticate</span> <span><span lang="" about="/user/21" typeof="schema:Person" property="schema:name" datatype="">淺唱寂寞╮</span></span> <span>2021-01-28 07:05:09</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I'm randomly facing an authentication error using library exchangelib:</p> <pre><code>from exchangelib import DELEGATE, Account, Credentials creds = Credentials( username=username, password=pw) account = Account( primary_smtp_address=mailbox_mail, credentials=creds, autodiscover=True, access_type=DELEGATE ) </code></pre> <p>The definition of the account variable causes the following error, but can't find why or anything useful in the relative documentation:</p> <pre><code>[2020-09-03 15:00:56,588] {taskinstance.py:1059} ERROR - 'www-authenticate' Traceback (most recent call last) File "/opt/python3.6/lib/python3.6/site-packages/cached_property.py", line 69, in __get_ return obj_dict[name KeyError: 'root During handling of the above exception, another exception occurred Traceback (most recent call last) File "/usr/local/lib/airflow/airflow/models/taskinstance.py", line 930, in _run_raw_tas result = task_copy.execute(context=context File "/usr/local/lib/airflow/airflow/operators/python_operator.py", line 113, in execut return_value = self.execute_callable( File "/usr/local/lib/airflow/airflow/operators/python_operator.py", line 118, in execute_callabl return self.python_callable(*self.op_args, **self.op_kwargs File "/home/airflow/gcs/dags/dg_functions/dg_flash_news_competitiva_mail/fun_flash_news_extract.py", line 34, in flash_news_extractio inbox = account.root / 'Top of Information Store' / 'Inbox File "/opt/python3.6/lib/python3.6/site-packages/cached_property.py", line 73, in __get_ return obj_dict.setdefault(name, self.func(obj) File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/account.py", line 270, in roo return Root.get_distinguished(account=self File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/folders/roots.py", line 109, in get_distinguishe folder=cls(account=account, name=cls.DISTINGUISHED_FOLDER_ID, is_distinguished=True File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/folders/base.py", line 487, in resolv folders = list(FolderCollection(account=account, folders=[folder]).resolve() File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/folders/collections.py", line 256, in resolv additional_fields=additional_field File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/folders/collections.py", line 319, in get_folder shape=ID_ONLY File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/services/get_folder.py", line 34, in cal shape=shape File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/services/common.py", line 540, in _pool_request for elem in self._get_elements(payload=payload_func(chunk, **kwargs)) File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/services/common.py", line 84, in _get_element response = self._get_response_xml(payload=payload File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/services/common.py", line 162, in _get_response_xm stream=self.streaming File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/util.py", line 715, in post_ratelimite stream=stream File "/opt/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 578, in pos return self.request('POST', url, data=data, json=json, **kwargs File "/opt/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 530, in reques resp = self.send(prep, **send_kwargs File "/opt/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 650, in sen r = dispatch_hook('response', hooks, r, **kwargs File "/opt/python3.6/lib/python3.6/site-packages/requests/hooks.py", line 31, in dispatch_hoo _hook_data = hook(hook_data, **kwargs File "/opt/python3.6/lib/python3.6/site-packages/requests_ntlm/requests_ntlm.py", line 151, in response_hoo kwarg File "/opt/python3.6/lib/python3.6/site-packages/requests_ntlm/requests_ntlm.py", line 103, in retry_using_http_NTLM_aut auth_header_value = response2.headers[auth_header_field File "/opt/python3.6/lib/python3.6/site-packages/requests/structures.py", line 54, in __getitem_ return self._store[key.lower()][1 KeyError: 'www-authenticate </code></pre> <p>It's strange because this error happens in a way it seems random. When this error occurs I just re-run the code and it immediately works.</p> <p>I use exchangelib==3.2.0 and Python 3.7.</p> <p>EDIT: Following you can find an OK log and a KO log:</p> <p>OK LOG:</p> <pre><code>2020-09-04 10:12:24 DEBUG Waiting for autodiscover_cache lock 2020-09-04 10:12:24 DEBUG autodiscover_cache lock acquired 2020-09-04 10:12:24 DEBUG Server [server_name]: Created session 29854 2020-09-04 10:12:24 DEBUG Cache hit for key ([domain_name], Credentials([domaint][user], '********')): https://[server_name]/Autodiscover/Autodiscover.xml 2020-09-04 10:12:24 DEBUG Server [server_name]: Waiting for session 2020-09-04 10:12:24 DEBUG Server [server_name]: Got session 29854 2020-09-04 10:12:24 DEBUG Session 29854 thread 140450161141504: retry 0 timeout 10 POST'ing to https://[server_name]/Autodiscover/Autodiscover.xml after 10s wait 2020-09-04 10:12:24 DEBUG Starting new HTTPS connection (1): [server_name]:443 2020-09-04 10:12:24 DEBUG https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 401 0 2020-09-04 10:12:24 DEBUG https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 401 0 2020-09-04 10:12:24 DEBUG https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 200 1512 2020-09-04 10:12:24 DEBUG Retry: 0 Waited: 10 Timeout: 10 Session: 29854 Thread: 140450161141504 Auth type: &lt;requests_ntlm.requests_ntlm.HttpNtlmAuth object at 0x7fbd16c577c0&gt; URL: https://[server_name]/Autodiscover/Autodiscover.xml HTTP adapter: &lt;requests.adapters.HTTPAdapter object at 0x7fbd16c576d0&gt; Allow redirects: False Streaming: False Response time: 0.45260270000017044 Status code: 200 Request headers: {'User-Agent': 'exchangelib/3.2.0 (python-requests/2.24.0)', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'Keep-Alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '363', 'Authorization': 'NTLM TlRMTVNTUAADAAAAGAAYAIQAAADcANwAnAAAABAAEABYAAAAHAAcAGgAAAAAAAAAhAAAABAAEAB4AQAANYKJ4gYBsR0AAAAPub38DriCTdGYXyBeyEmnhFcASQBOAEQAUgBPAE8AVABkAGEAdABhAGcAbwB2AGUAcgBuAGEAbgBjAGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5YSqd4DM1UDCWxxNIp33ZQEBAAAAAAAAhiCP86OC1gHUAV9Y4d/fWgAAAAACABAAVwBJAE4ARABSAE8ATwBUAAEADgBXAE0ATwBFAFgAMAA0AAQAGAB3AGkAbgBkAC4AcgBvAG8AdAAuAGkAdAADACgAVwBNAE8ARQBYADAANAAuAHcAaQBuAGQALgByAG8AbwB0AC4AaQB0AAUADgByAG8AbwB0AC4AaQB0AAcACACGII/zo4LWAQYABAACAAAACgAQADeb/GQ6brEyEkTMYIxALRMAAAAAAAAAAGR+d4O+5tqPvV7v0nc4Lxo='} Response headers: {'Cache-Control': 'private', 'Content-Length': '1512', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Server': 'Microsoft-IIS/8.5', 'Set-Cookie': 'X-BackEndCookie=S-1-5-21-842925246-725345543-1163770773-1933531=u56Lnp2ejJqBy82bmZqeycbSx8ucztLLxsjH0seczJ3SnMjKxprNmpnGyZyZgYHNz83P0s7P0s/Lq87Pxc7NxcrMgY2QkIvRlouBzg==; expires=Sun, 04-Oct-2020 10:12:53 GMT; path=/Autodiscover; secure; HttpOnly', 'Persistent-Auth': 'true', 'request-id': '75ad68fb-99a1-490d-a755-21df9b7dc8d7', 'X-CalculatedBETarget': 'wivex01.[domain_name]', 'X-DiagInfo': 'WIVEX01', 'X-BEServer': 'WIVEX01', 'X-AspNet-Version': '4.0.30319', 'X-Powered-By': 'ASP.NET, ARR/3.0', 'X-FEServer': 'WMOEX04', 'Date': 'Fri, 04 Sep 2020 10:12:24 GMT'} Request data: b'&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n&lt;Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006"&gt;&lt;Request&gt;&lt;EMailAddress&gt;[mail_address]&lt;/EMailAddress&gt;&lt;AcceptableResponseSchema&gt;http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a&lt;/AcceptableResponseSchema&gt;&lt;/Request&gt;&lt;/Autodiscover&gt;' Response data: b'&lt;?xml version="1.0" encoding="utf-8"?&gt;\r\n&lt;Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006"&gt;\r\n &lt;Response xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a"&gt;\r\n &lt;User&gt;\r\n &lt;DisplayName&gt;Servizio Data Governance BDA&lt;/DisplayName&gt;\r\n &lt;LegacyDN&gt;/o=Wind/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=30cb9e003a984ecab16ac41684388a50-Servizio Data Gover&lt;/LegacyDN&gt;\r\n &lt;AutoDiscoverSMTPAddress&gt;[mail_address]&lt;/AutoDiscoverSMTPAddress&gt;\r\n &lt;DeploymentId&gt;a97bb132-fdfa-4fba-876f-79442c336e12&lt;/DeploymentId&gt;\r\n &lt;/User&gt;\r\n &lt;Account&gt;\r\n &lt;AccountType&gt;email&lt;/AccountType&gt;\r\n &lt;Action&gt;settings&lt;/Action&gt;\r\n &lt;MicrosoftOnline&gt;False&lt;/MicrosoftOnline&gt;\r\n &lt;Protocol&gt;\r\n &lt;Type&gt;EXCH&lt;/Type&gt;\r\n &lt;Server&gt;9dd010c4-db51-45e2-a8b8-1d37b45950ef@[domain_name]&lt;/Server&gt;\r\n &lt;ServerDN&gt;/o=Wind/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=9dd010c4-db51-45e2-a8b8-1d37b45950ef@[domain_name]&lt;/ServerDN&gt;\r\n &lt;ServerVersion&gt;73C186B1&lt;/ServerVersion&gt;\r\n &lt;MdbDN&gt;/o=Wind/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=9dd010c4-db51-45e2-a8b8-1d37b45950ef@[domain_name]/cn=Microsoft Private MDB&lt;/MdbDN&gt;\r\n &lt;PublicFolderServer&gt;[public_server]&lt;/PublicFolderServer&gt;\r\n &lt;AD&gt;DCIVWR07.[domain_name]&lt;/AD&gt;\r\n &lt;ASUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/ASUrl&gt;\r\n &lt;EwsUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/EwsUrl&gt;\r\n &lt;EmwsUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/EmwsUrl&gt;\r\n &lt;SharingUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/SharingUrl&gt;\r\n &lt;EcpUrl&gt;https://[public_server_name]/owa/&lt;/EcpUrl&gt;\r\n &lt;EcpUrl-um&gt;?path=/options/callanswering&lt;/EcpUrl-um&gt;\r\n &lt;EcpUrl-aggr&gt;?path=/options/connectedaccounts&lt;/EcpUrl-aggr&gt;\r\n &lt;EcpUrl-mt&gt;options/ecp/PersonalSettings/DeliveryReport.aspx?rfr=olk&amp;amp;exsvurl=1&amp;amp;IsOWA=&amp;lt;IsOWA&amp;gt;&amp;amp;MsgID=&amp;lt;MsgID&amp;gt;&amp;amp;Mbx=&amp;lt;Mbx&amp;gt;&amp;amp;realm=[realm]&lt;/EcpUrl-mt&gt;\r\n &lt;EcpUrl-ret&gt;?path=/options/retentionpolicies&lt;/EcpUrl-ret&gt;\r\n &lt;EcpUrl-sms&gt;?path=/options/textmessaging&lt;/EcpUrl-sms&gt;\r\n &lt;EcpUrl-photo&gt;?path=/options/myaccount/action/photo&lt;/EcpUrl-photo&gt;\r\n &lt;EcpUrl-tm&gt;options/ecp/?rfr=olk&amp;amp;ftr=TeamMailbox&amp;amp;exsvurl=1&amp;amp;realm=[realm]&lt;/EcpUrl-tm&gt;\r\n &lt;EcpUrl-tmCreating&gt;options/ecp/?rfr=olk&amp;amp;ftr=TeamMailboxCreating&amp;amp;SPUrl=&amp;lt;SPUrl&amp;gt;&amp;amp;Title=&amp;lt;Title&amp;gt;&amp;amp;SPTMAppUrl=&amp;lt;SPTMAppUrl&amp;gt;&amp;amp;exsvurl=1&amp;amp;realm=[realm]&lt;/EcpUrl-tmCreating&gt;\r\n &lt;EcpUrl-tmEditing&gt;options/ecp/?rfr=olk&amp;amp;ftr=TeamMailboxEditing&amp;amp;Id=&amp;lt;Id&amp;gt;&amp;amp;exsvurl=1&amp;amp;realm=[realm]&lt;/EcpUrl-tmEditing&gt;\r\n &lt;EcpUrl-extinstall&gt;?path=/options/manageapps&lt;/EcpUrl-extinstall&gt;\r\n &lt;OOFUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/OOFUrl&gt;\r\n &lt;UMUrl&gt;https://[public_server_name]/EWS/UM2007Legacy.asmx&lt;/UMUrl&gt;\r\n &lt;OABUrl&gt;https://[public_server_name]/OAB/95ecfb44-4ba6-46e0-88b1-8a6622de13e8/&lt;/OABUrl&gt;\r\n &lt;ServerExclusiveConnect&gt;off&lt;/ServerExclusiveConnect&gt;\r\n &lt;/Protocol&gt;\r\n &lt;Protocol&gt;\r\n &lt;Type&gt;EXPR&lt;/Type&gt;\r\n &lt;Server&gt;[public_server_name]&lt;/Server&gt;\r\n &lt;SSL&gt;On&lt;/SSL&gt;\r\n &lt;AuthPackage&gt;Ntlm&lt;/AuthPackage&gt;\r\n &lt;ASUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/ASUrl&gt;\r\n &lt;EwsUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/EwsUrl&gt;\r\n &lt;EmwsUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/EmwsUrl&gt;\r\n &lt;SharingUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/SharingUrl&gt;\r\n &lt;EcpUrl&gt;https://[public_server_name]/owa/&lt;/EcpUrl&gt;\r\n &lt;EcpUrl-um&gt;?path=/options/callanswering&lt;/EcpUrl-um&gt;\r\n &lt;EcpUrl-aggr&gt;?path=/options/connectedaccounts&lt;/EcpUrl-aggr&gt;\r\n &lt;EcpUrl-mt&gt;options/ecp/PersonalSettings/DeliveryReport.aspx?rfr=olk&amp;amp;exsvurl=1&amp;amp;IsOWA=&amp;lt;IsOWA&amp;gt;&amp;amp;MsgID=&amp;lt;MsgID&amp;gt;&amp;amp;Mbx=&amp;lt;Mbx&amp;gt;&amp;amp;realm=[realm]&lt;/EcpUrl-mt&gt;\r\n &lt;EcpUrl-ret&gt;?path=/options/retentionpolicies&lt;/EcpUrl-ret&gt;\r\n &lt;EcpUrl-sms&gt;?path=/options/textmessaging&lt;/EcpUrl-sms&gt;\r\n &lt;EcpUrl-photo&gt;?path=/options/myaccount/action/photo&lt;/EcpUrl-photo&gt;\r\n &lt;EcpUrl-tm&gt;options/ecp/?rfr=olk&amp;amp;ftr=TeamMailbox&amp;amp;exsvurl=1&amp;amp;realm=[realm]&lt;/EcpUrl-tm&gt;\r\n &lt;EcpUrl-tmCreating&gt;options/ecp/?rfr=olk&amp;amp;ftr=TeamMailboxCreating&amp;amp;SPUrl=&amp;lt;SPUrl&amp;gt;&amp;amp;Title=&amp;lt;Title&amp;gt;&amp;amp;SPTMAppUrl=&amp;lt;SPTMAppUrl&amp;gt;&amp;amp;exsvurl=1&amp;amp;realm=[realm]&lt;/EcpUrl-tmCreating&gt;\r\n &lt;EcpUrl-tmEditing&gt;options/ecp/?rfr=olk&amp;amp;ftr=TeamMailboxEditing&amp;amp;Id=&amp;lt;Id&amp;gt;&amp;amp;exsvurl=1&amp;amp;realm=[realm]&lt;/EcpUrl-tmEditing&gt;\r\n &lt;EcpUrl-extinstall&gt;?path=/options/manageapps&lt;/EcpUrl-extinstall&gt;\r\n &lt;OOFUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/OOFUrl&gt;\r\n &lt;UMUrl&gt;https://[public_server_name]/EWS/UM2007Legacy.asmx&lt;/UMUrl&gt;\r\n &lt;OABUrl&gt;https://[public_server_name]/OAB/95ecfb44-4ba6-46e0-88b1-8a6622de13e8/&lt;/OABUrl&gt;\r\n &lt;ServerExclusiveConnect&gt;on&lt;/ServerExclusiveConnect&gt;\r\n &lt;CertPrincipalName&gt;msstd:wmae.[cert].it&lt;/CertPrincipalName&gt;\r\n &lt;EwsPartnerUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/EwsPartnerUrl&gt;\r\n &lt;GroupingInformation&gt;STMOLFETTA&lt;/GroupingInformation&gt;\r\n &lt;/Protocol&gt;\r\n &lt;Protocol&gt;\r\n &lt;Type&gt;WEB&lt;/Type&gt;\r\n &lt;Internal&gt;\r\n &lt;OWAUrl AuthenticationMethod="Basic, Fba"&gt;https://[public_server_name]/owa/&lt;/OWAUrl&gt;\r\n &lt;Protocol&gt;\r\n &lt;Type&gt;EXCH&lt;/Type&gt;\r\n &lt;ASUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/ASUrl&gt;\r\n &lt;/Protocol&gt;\r\n &lt;/Internal&gt;\r\n &lt;External&gt;\r\n &lt;OWAUrl AuthenticationMethod="Fba"&gt;https://[public_server_name]/owa/&lt;/OWAUrl&gt;\r\n &lt;Protocol&gt;\r\n &lt;Type&gt;EXPR&lt;/Type&gt;\r\n &lt;ASUrl&gt;https://[public_server_name]/EWS/Exchange.asmx&lt;/ASUrl&gt;\r\n &lt;/Protocol&gt;\r\n &lt;/External&gt;\r\n &lt;/Protocol&gt;\r\n &lt;/Account&gt;\r\n &lt;/Response&gt;\r\n&lt;/Autodiscover&gt;' 2020-09-04 10:12:24 DEBUG No retry: wrong status code 200 2020-09-04 10:12:24 DEBUG Session 29854 thread 140450161141504: Useful response from https://[server_name]/Autodiscover/Autodiscover.xml 2020-09-04 10:12:24 DEBUG Server [server_name]: Releasing session 29854 2020-09-04 10:12:24 INFO Step 5: Checking response 2020-09-04 10:12:24 DEBUG Released autodiscover_cache_lock 2020-09-04 10:12:24 DEBUG Waiting for _protocol_cache_lock 2020-09-04 10:12:24 DEBUG Protocol __call__ cache miss. Adding key '('https://[public_server_name]/EWS/Exchange.asmx', Credentials('[domain]\[user]', '********'))' 2020-09-04 10:12:24 DEBUG Requesting b'&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n&lt;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"&gt;&lt;s:Header&gt;&lt;t:RequestServerVersion Version="Exchange2019"/&gt;&lt;/s:Header&gt;&lt;s:Body&gt;&lt;m:ResolveNames ReturnFullContactData="false"&gt;&lt;m:UnresolvedEntry&gt;[domain]\[user]&lt;/m:UnresolvedEntry&gt;&lt;/m:ResolveNames&gt;&lt;/s:Body&gt;&lt;/s:Envelope&gt;' from https://[public_server_name]/EWS/Exchange.asmx 2020-09-04 10:12:24 DEBUG Trying to get service auth type for https://[public_server_name]/EWS/Exchange.asmx 2020-09-04 10:12:24 DEBUG Starting new HTTPS connection (1): [public_server_name]:443 2020-09-04 10:12:24 DEBUG https://[public_server_name]:443 "POST /EWS/Exchange.asmx HTTP/1.1" 401 0 2020-09-04 10:12:24 DEBUG Request headers: {'User-Agent': 'exchangelib/3.2.0 (python-requests/2.24.0)', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '466'} 2020-09-04 10:12:24 DEBUG Response headers: {'Server': 'Microsoft-IIS/8.5', 'WWW-Authenticate': 'Negotiate, NTLM', 'request-id': '5035ba0e-5caf-4b3d-8c39-07f76e04a0da', 'X-Powered-By': 'ASP.NET, ARR/3.0', 'X-FEServer': 'WIVEX02', 'Date': 'Fri, 04 Sep 2020 10:12:24 GMT', 'Content-Length': '0'} 2020-09-04 10:12:24 DEBUG Auth type is NTLM 2020-09-04 10:12:24 DEBUG Server [public_server_name]: Created session 25722 2020-09-04 10:12:24 DEBUG Added account: [account_mail] </code></pre> <p>KO LOG:</p> <pre><code>2020-09-04 09:58:47 DEBUG Waiting for autodiscover_cache lock 2020-09-04 09:58:47 DEBUG autodiscover_cache lock acquired 2020-09-04 09:58:47 DEBUG Server [server_name]: Created session 26384 2020-09-04 09:58:47 DEBUG Cache hit for key ([domain_name], Credentials([domaint][user], '********')): https://[server_name]/Autodiscover/Autodiscover.xml 2020-09-04 09:58:47 DEBUG Server [server_name]: Waiting for session 2020-09-04 09:58:47 DEBUG Server [server_name]: Got session 26384 2020-09-04 09:58:47 DEBUG Session 26384 thread 140624867845888: retry 0 timeout 10 POST'ing to https://[server_name]/Autodiscover/Autodiscover.xml after 10s wait 2020-09-04 09:58:47 DEBUG Starting new HTTPS connection (1): [server_name]:443 2020-09-04 09:58:48 DEBUG https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 401 0 2020-09-04 09:58:48 DEBUG https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 502 1477 2020-09-04 09:58:48 ERROR KeyError: 'www-authenticate' Retry: 0 Waited: 10 Timeout: 10 Session: 26384 Thread: 140624867845888 Auth type: &lt;requests_ntlm.requests_ntlm.HttpNtlmAuth object at 0x7fe5c41a37c0&gt; URL: https://[server_name]/Autodiscover/Autodiscover.xml HTTP adapter: &lt;requests.adapters.HTTPAdapter object at 0x7fe5c41a36d0&gt; Allow redirects: False Streaming: False Response time: 0.3348593030000302 Status code: 503 Request headers: {'Content-Type': 'text/xml; charset=utf-8', 'Accept-Encoding': 'gzip, deflate'} Response headers: {} Request data: b'&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n&lt;Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006"&gt;&lt;Request&gt;&lt;EMailAddress&gt;[email_address]&lt;/EMailAddress&gt;&lt;AcceptableResponseSchema&gt;http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a&lt;/AcceptableResponseSchema&gt;&lt;/Request&gt;&lt;/Autodiscover&gt;' Response data: b'' 2020-09-04 09:58:48 DEBUG Server [server_name]: Retiring session 26384 2020-09-04 09:58:48 DEBUG Server [server_name]: Created session 26493 2020-09-04 09:58:48 DEBUG Server [server_name]: Releasing session 26493 </code></pre> <p>Please, can someone help me?</p> <br /><h3>回答1:</h3><br /><p>I just pushed a commit that might fix this for you: https://github.com/ecederstrand/exchangelib/commit/c7b4b5a89c5518a6d19b7e88c5a945b9083b15d0</p> <p>You need to use it in combination with a retry policy to paper over this internal error from <code>requests_ntlm</code>.</p> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/63726671/exchangelib-error-in-python-www-authenticate</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/email" hreflang="zh-hans">email</a></div> <div class="field--item"><a href="/tag/exchangewebservices" hreflang="zh-hans">exchangewebservices</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Wed, 27 Jan 2021 23:05:09 +0000 淺唱寂寞╮ 4024091 at https://www.e-learn.cn exchangelib - All steps in the autodiscover protocol failed https://www.e-learn.cn/topic/3674781 <span>exchangelib - All steps in the autodiscover protocol failed</span> <span><span lang="" about="/user/185" typeof="schema:Person" property="schema:name" datatype="">泪湿孤枕</span></span> <span>2020-06-27 07:21:19</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I have a problem with using exchangelib in python. I try this example code:</p> <pre class="lang-python prettyprint-override"><code>from exchangelib import DELEGATE, Account, Credentials creds = Credentials( username='xxxx\\username', password="mypassword" ) account = Account( primary_smtp_address='surname.name@xxxx.fr', credentials=creds, autodiscover=True, access_type=DELEGATE ) # Print first 10 inbox messages in reverse order for item in account.inbox.all().order_by('-datetime_received')[:10]: print(item.subject, item.body, item.attachments) </code></pre> <p>I tried differents usernames but nothing works and I have always the same error message : </p> <blockquote> <p><code>AutoDiscoverFailed: All steps in the autodiscover protocol failed</code></p> </blockquote> <p>By the way, just in case it could help, i tried to use the Exchange Web service coded for C# and it works perfectly fine with this creds, i can send a mail:</p> <pre class="lang-cs prettyprint-override"><code>static void Main(string[] args) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // The last parameter is the domain name service.Credentials = new WebCredentials("username", "password", "xxxx.lan"); service.AutodiscoverUrl("surname.name@xxxx.fr", RedirectionUrlValidationCallback); EmailMessage email = new EmailMessage(service); email.ToRecipients.Add("surname.name@xxxx.fr"); email.Subject = "salut "; email.Body = new MessageBody("corps du message"); email.Send(); } private static bool RedirectionUrlValidationCallback(string redirectionUrl) { // The default for the validation callback is to reject the URL. bool result = false; Uri redirectionUri = new Uri(redirectionUrl); /* Validate the contents of the redirection URL. In this simple validation callback, the redirection URL is considered valid if it is using HTTPS to encrypt the authentication credentials. */ if (redirectionUri.Scheme == "https") { result = true; } return result; } </code></pre> <p>Thanks in advance !</p> <br /><h3>回答1:</h3><br /><p>I finally succeed with this configuration:</p> <pre class="lang-python prettyprint-override"><code>from exchangelib import DELEGATE, Account, Credentials, Configuration creds = Credentials( username="domain_name\\username", password="password" ) config = Configuration(server='mail.solutec.fr', credentials=creds) account = Account( primary_smtp_address="my email address", autodiscover=False, config=config, access_type=DELEGATE ) </code></pre> <p>For those who will have the same problem, you can find your domain_name by right-clicking on "Computer" and Properties. Username and Password are the one you use to connect to your company mailbox for example. For the server in Configuration, for me this one works: "mail.solutec.fr", where solutec is the name of my company and fr for France.</p> <p>Looks like this autodiscover guy really doesn't like me ^^</p> <p>Thanks for your help anyway and have a good day !</p> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/46525041/exchangelib-all-steps-in-the-autodiscover-protocol-failed</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/office365" hreflang="zh-hans">office365</a></div> <div class="field--item"><a href="/tag/exchange-server" hreflang="zh-hans">exchange-server</a></div> <div class="field--item"><a href="/tag/exchangewebservices" hreflang="zh-hans">exchangewebservices</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Fri, 26 Jun 2020 23:21:19 +0000 泪湿孤枕 3674781 at https://www.e-learn.cn SSL: CERTIFICATE_VERIFY_FAILED when connecting to a company Exchange Server https://www.e-learn.cn/topic/3208748 <span>SSL: CERTIFICATE_VERIFY_FAILED when connecting to a company Exchange Server</span> <span><span lang="" about="/user/221" typeof="schema:Person" property="schema:name" datatype="">雨燕双飞</span></span> <span>2020-01-14 04:08:46</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I try to send mails from out company exchange server via Python. My problem is, that I get a SSL error. I read a lot of pem-, cer-, crt-files, but I can not connect all these information to have success. I am sure, that if one can fix the issue in my little example script, one could fix the exchange script, too.</p> <p>I read a lot about certificates and ca_bundles, but I don't know how to apply all of that to my issue.</p> <p><strong>Example-Script</strong>:</p> <pre><code>import requests requests.get('https://mail.ourserver.loc') </code></pre> <p><strong>Error</strong>:</p> <pre><code>C:\Python\python.exe "PATHtoMYproject/testing.py" Traceback (most recent call last): File "C:\Python\lib\site-packages\urllib3\contrib\pyopenssl.py", line 441, in wrap_socket cnx.do_handshake() File "C:\Python\lib\site-packages\OpenSSL\SSL.py", line 1806, in do_handshake self._raise_ssl_error(self._ssl, result) File "C:\Python\lib\site-packages\OpenSSL\SSL.py", line 1546, in _raise_ssl_error _raise_current_error() File "C:\Python\lib\site-packages\OpenSSL\_util.py", line 54, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')] During handling of the above exception, another exception occurred: Traceback (most recent call last): [.. a lot of text..] ssl.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",) During handling of the above exception, another exception occurred: Traceback (most recent call last): [.. a lot of text..] urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='mail.ourserver.loc', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)) </code></pre> <p><strong>Exchange-Script</strong>:</p> <pre><code>from exchangelib import DELEGATE, Account, Credentials, Configuration, Message import os import urllib3 urllib3.disable_warnings() creds = Credentials(username='EX\\GE-USR', password='secret') config = Configuration(server='mail.ourserver.loc', credentials=creds) account = Account(primary_smtp_address="user-name@ex-ample.com", autodiscover=False, config=config, access_type=DELEGATE) def send(email_receiver): m = Message( account=account, subject='This is a test!', body='Hallo', to_recipients=[email_receiver]) m.send_and_save() receiver = 'user-name@ex-ample.com' send(email_receiver=receiver) print('Finish') </code></pre> <p><strong>Error</strong>:</p> <pre><code>C:\Python\python.exe "PATHtoMYproject//exchange_main.py" Traceback (most recent call last): File "C:\Python\lib\site-packages\urllib3\contrib\pyopenssl.py", line 441, in wrap_socket cnx.do_handshake() File "C:\Python\lib\site-packages\OpenSSL\SSL.py", line 1806, in do_handshake self._raise_ssl_error(self._ssl, result) File "C:\Python\lib\site-packages\OpenSSL\SSL.py", line 1546, in _raise_ssl_error _raise_current_error() File "C:\Python\lib\site-packages\OpenSSL\_util.py", line 54, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')] During handling of the above exception, another exception occurred: Traceback (most recent call last): [.. a lot of text..] ssl.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\lib\site-packages\requests\adapters.py", line 440, in send timeout=timeout File "C:\Python\lib\site-packages\urllib3\connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "C:\Python\lib\site-packages\urllib3\util\retry.py", line 388, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='mail.ourserver.loc', port=443): Max retries exceeded with url: /EWS/Exchange.asmx (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)) During handling of the above exception, another exception occurred: Traceback (most recent call last): [.. a lot of text..] requests.exceptions.ConnectionError: HTTPSConnectionPool(host='mail.ourserver.loc', port=443): Max retries exceeded with url: /EWS/Exchange.asmx (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)) Process finished with exit code 1url: /EWS/Exchange.asmx (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)) During handling of the above exception, another exception occurred: Traceback (most recent call last): [.. a lot of text..] requests.exceptions.ConnectionError: HTTPSConnectionPool(host='mail.ourserver.loc', port=443): Max retries exceeded with url: /EWS/Exchange.asmx (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",),)) Process finished with exit code 1 </code></pre> <br /><h3>回答1:</h3><br /><p>I got it to work. I uninstalled pyopenssl and the error of my <strong>Example-Script</strong> changed to this:</p> <pre><code>requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) </code></pre> <p>Then I found some useful commands to get into the pem-file topic. Basically, I just had to add the certificate in order to solve my problem. Most people said that I have to add my certificate to a pem-file like cacert.pem, but it is possible that you have several modules installed that use different files. I found this topic very useful to find out the location of my cacert.pem file: LINK_1 e. g.:</p> <p><code>python -c "import requests; print requests.certs.where()"</code></p> <p>Next I had the problem, that I didn't have a certificate to add to the pem-file. Somehow my browser was able to send a https request, so the browser was able to use a certificate from windows. This link brought the solution.</p> <pre><code>import ssl context = ssl.create_default_context() der_certs = context.get_ca_certs(binary_form=True) pem_certs = [ssl.DER_cert_to_PEM_cert(der) for der in der_certs] with open('wincacerts.pem', 'w') as outfile: for pem in pem_certs: outfile.write(pem + '\n') </code></pre> <p>I exported the certificate from windows and added the file to my request-script:</p> <pre><code>import os import requests root_path = os.getcwd() path_pem=os.path.join(root_path, 'wincacerts.pem') requests.get('https://mail.ourserver.loc', verify=path_pem) </code></pre> <p>Back to my exchange script I added these lines to the beginning and added my certificate. I simply renamed the file from .pem to .crt. I was then able to send an email via the exchange server to myself.</p> <pre><code>root_path = os.getcwd() path_pem=os.path.join(root_path, 'files', 'wincacerts.crt') class RootCAAdapter(requests.adapters.HTTPAdapter): # An HTTP adapter that uses a custom root CA certificate at a hard coded location def cert_verify(self, conn, url, verify, cert): cert_file = { 'mail.ourserver.loc': path_pem, 'mail.internal': '/path/to/mail.internal.crt' }[urlparse(url).hostname] super(RootCAAdapter, self).cert_verify(conn=conn, url=url, verify=cert_file, cert=cert) # Tell exchangelib to use this adapter class instead of the default BaseProtocol.HTTP_ADAPTER_CLS = RootCAAdapter </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/51262568/ssl-certificate-verify-failed-when-connecting-to-a-company-exchange-server</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/openssl" hreflang="zh-hans">OpenSSL</a></div> <div class="field--item"><a href="/tag/exchangewebservices" hreflang="zh-hans">exchangewebservices</a></div> <div class="field--item"><a href="/tag/tls12" hreflang="zh-hans">tls1.2</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Mon, 13 Jan 2020 20:08:46 +0000 雨燕双飞 3208748 at https://www.e-learn.cn How can I get the latest emails from all folders with exchangelib? https://www.e-learn.cn/topic/3100443 <span>How can I get the latest emails from all folders with exchangelib?</span> <span><span lang="" about="/user/35" typeof="schema:Person" property="schema:name" datatype="">99封情书</span></span> <span>2020-01-04 16:56:54</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>Currently, I use</p> <pre><code>latest_mails = account.inbox.filter(datetime_received__gt=emails_since) </code></pre> <p>But it seems to miss received emails which are in subfolders.</p> <p>Printing all folders with</p> <pre><code>for f in account.root.get_folders(): print(f) </code></pre> <p>gives something like</p> <pre><code>Calendar (Kalender) Contacts (Kontakte) Contacts (Vorgeschlagene Kontakte) Folder (AllItems) Folder (Calendar Logging) Folder (Common Views) Folder (Conversation Action Settings) Folder (Deferred Action) Folder (Deletions) Folder (Erinnerungen) Folder (ExchangeSyncData) Folder (Finder) Folder (Infected Items) Folder (Journal) Folder (Location) Folder (MailboxAssociations) Folder (Notizen) Folder (Recipient Cache) Folder (Recoverable Items) Folder (Schedule) Folder (Shortcuts) Folder (Spooler Queue) Folder (System) Folder (Versions) Folder (Views) Folder (WorkingSet) Messages (Postausgang) Messages (Posteingang) Messages (foo) Messages (bar) Messages (something is) Messages (here) Messages (Gelöschte Elemente) Messages (Gesendete Elemente) Messages (Junk-E-Mail) Messages (Meine Kontakte) Messages (MyContactsExtended) Messages (Nachverfolgte E-Mail-Verarbeitung) Messages (Zugang) Tasks (Aufgaben) Tasks (Aufgabensuche) </code></pre> <p>So I only want to look at the "Messages" folders, but at all of them. Is that possible (without using <code>account.root.get_folders()</code>) and looping over the results (which took about 5 minutes)</p> <br /><h3>回答1:</h3><br /><p>You're correct that <code>.filter()</code> only works on the folder you call it on, not subfolders. I'm pretty sure EWS only supports searching one folder at a time.</p> <p>You should be able to do something like this to speed things up a little bit:</p> <pre><code>from exchangelib.folders import Messages for f in account.folders[Message]: for i in f.filter(datetime_received__gt=emails_since): print(i) </code></pre> <p>But <code>Folder</code> type folders can also contain <code>Message</code> items, so depending on your needs you may also have to visit those.</p> <p><code>f.supported_item_models</code> will tell you which item types a given folder can contain.</p> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/45935701/how-can-i-get-the-latest-emails-from-all-folders-with-exchangelib</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Sat, 04 Jan 2020 08:56:54 +0000 99封情书 3100443 at https://www.e-learn.cn Python exchangelib: check if item is a message or not https://www.e-learn.cn/topic/2783744 <span>Python exchangelib: check if item is a message or not</span> <span><span lang="" about="/user/24" typeof="schema:Person" property="schema:name" datatype="">Deadly</span></span> <span>2019-12-23 02:45:11</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I got an error when retrieve items using exchangelib. Is there any method to detect whether the item is an email, and if not, just ignore it? The following code raises <code>AttributeError: 'MeetingRequest' object has no attribute 'flag')</code> since meeting requests don't have a <code>flag</code> field. Or is there any method to view the type of the item?</p> <pre><code>import re import sys from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \ EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Message, \ Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, \ HTMLBody, Build, Version from datetime import datetime, timedelta import pytz tz = EWSTimeZone.timezone('Asia/Hong_Kong') creds = Credentials( username='domain\userID', password='password') ) account = Account( primary_smtp_address='myemail@domain', credentials=creds, autodiscover=True, access_type=DELEGATE) class Flag(ExtendedProperty): property_tag = 0x1090 property_type = 'Integer' Message.register('flag', Flag) if(len(sys.argv) == 1): yesterday = tz.localize(EWSDateTime.now() - timedelta(days=3)) today = tz.localize(EWSDateTime.now()) fYear= yesterday.year fMonth= yesterday.month fDay= yesterday.day tYear = today.year tMonth = today.month tDay = today.day elif(len(sys.argv) == 3): fromDate = sys.argv[1] toDate = sys.argv[2] fYear = fromDate[:4] fMonth = fromDate[4:6] fDay = fromDate[-2:] tYear = toDate[:4] tMonth = toDate[4:6] tDay = toDate[-2:] for item in account.inbox.filter(datetime_received__range=( #tz.localize(EWSDateTime.now() - timedelta(days=1)), #tz.localize(EWSDateTime.now()) tz.localize(EWSDateTime(int(fYear), int(fMonth), int(fDay))), tz.localize(EWSDateTime(int(tYear), int(tMonth), int(tDay))) )): subA=item.subject snd=item.sender.email_address fg=str(item.flag) str(item.datetime_received.astimezone(pytz.timezone('Asia/Hong_Kong')).strftime("%a %b %d %H:%M:%S %Y")) rT = str(item.datetime_received.astimezone(pytz.timezone('Asia/Hong_Kong')).strftime("%Y-%m-%d %H:%M:%S")) cat=str(item.categories) if not subA: subA="" a="\"Inbox\",\""+snd+"\",\""+subA+"\",\""+rT+"\",\""+cat+"\",\""+fg+"\"" print(a) else: subA = re.sub('\"\,\"', '\\"\,\\"', subA.rstrip()) a="\"Inbox\",\""+snd+"\",\""+subA+"\",\""+rT+"\",\""+cat+"\",\""+fg+"\"" decoded = a.encode('utf-8').decode('utf-8') print(decoded) </code></pre> <br /><h3>回答1:</h3><br /><p>Just check the class of the returned item: <code>if type(item) == Message</code> and ignore the ones that don't match.</p> <p>If you want to avoid the cause of the error, you need to also register the <code>flag</code> property on the <code>MeetingRequest</code> class (and <code>MeetingResponse</code> and <code>MeetingCancellation</code> if you have those in your folder).</p> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/49013158/python-exchangelib-check-if-item-is-a-message-or-not</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Sun, 22 Dec 2019 18:45:11 +0000 Deadly 2783744 at https://www.e-learn.cn Mark email as read with exchangelib https://www.e-learn.cn/topic/2749826 <span>Mark email as read with exchangelib</span> <span><span lang="" about="/user/63" typeof="schema:Person" property="schema:name" datatype="">女生的网名这么多〃</span></span> <span>2019-12-22 05:37:19</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I am using Pythons <code>exchangelib</code> package. How can I mark an e-mail as read with exchangelib?</p> <p>I have had a look at the official GitHub exchangelib page for my query, but didn't find the answer.</p> <br /><h3>回答1:</h3><br /><p>To add to joe's comment, you must also 'save' the item for the flag to be permanent.</p> <pre><code>item.is_read = True item.save() </code></pre> <br /><br /><br /><h3>回答2:</h3><br /><p>To add to HeroicOlive's comment, if you specifically want to save the <code>is_read</code> value only, try:</p> <pre><code>item.is_read = True item.save(update_fields=['is_read']) </code></pre> <br /><br /><br /><h3>回答3:</h3><br /><p>item.is_read = True should do the trick where item is the message you want to mark read</p> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/45037322/mark-email-as-read-with-exchangelib</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/python-27" hreflang="zh-hans">python-2.7</a></div> <div class="field--item"><a href="/tag/email" hreflang="zh-hans">email</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Sat, 21 Dec 2019 21:37:19 +0000 女生的网名这么多〃 2749826 at https://www.e-learn.cn How can I send attachments in an email reply? https://www.e-learn.cn/topic/2220003 <span>How can I send attachments in an email reply?</span> <span><span lang="" about="/user/77" typeof="schema:Person" property="schema:name" datatype="">只愿长相守</span></span> <span>2019-12-11 07:05:07</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>I'm using the exchangelib package to connect to Exchange. I need to send attachments in a reply. When I send a normal message I add the attachment to the Message object like this:</p> <pre><code>message = Message() message.account = account message.subject = 'subject' message.body = 'text' message.to_recipients = [Mailbox(email_address='example@gmail.com')] message.cc_recipients = ['example2@gmail.com'] for attachment in attachments or []: with open(attachment['path'], 'rb') as f: file = FileAttachment(name=attachment['file_name'], content=f.read()) message.attach(file) </code></pre> <p>and to send a reply:</p> <pre><code>reply = message.reply( subject='Re: subject', body='texto', to_recipients=['example@gmail.com'] ) </code></pre> <p>This works, but I don't now how to add attachments to the reply. I tried to set the attributes "attachments" and "attach" but the object doesn't have them.</p> <br /><h3>回答1:</h3><br /><p>The <code>Message.reply()</code> method creates and sends a <code>ReplyToItem</code> item which doesn't support attachments. See https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/replytoitem</p> <p>So if you want to send a reply that has attachments, just create a normal Message item that has a <code>'Re: some subject'</code> title, contains the attachment, and quotes the original message, if that's needed.</p> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/52628766/how-can-i-send-attachments-in-an-email-reply</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/email" hreflang="zh-hans">email</a></div> <div class="field--item"><a href="/tag/attachment" hreflang="zh-hans">attachment</a></div> <div class="field--item"><a href="/tag/email-attachments" hreflang="zh-hans">email-attachments</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Tue, 10 Dec 2019 23:05:07 +0000 只愿长相守 2220003 at https://www.e-learn.cn Python/exchangelib - How to access shared public folders and calendars https://www.e-learn.cn/topic/2094316 <span>Python/exchangelib - How to access shared public folders and calendars</span> <span><span lang="" about="/user/227" typeof="schema:Person" property="schema:name" datatype="">烂漫一生</span></span> <span>2019-12-10 11:42:23</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>How can I connect to a shared public folder using exchangelib?</p> <pre><code>from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \ EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Message, \ Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, \ HTMLBody, Build, Version credentials = Credentials(username='DOMAIN\\username', password='password') config = Configuration(server='server', credentials=credentials, auth_type=NTLM, verify_ssl=False) account = Account(primary_smtp_address='user@email.com', config=config, autodiscover=False, access_type=DELEGATE) for i in account.root.get_folders(): print(i) </code></pre> <p>When I run the code above I get the output shown below. I'm pretty sure none of these options correspond to a shared public folder.</p> <blockquote> <p>Folder (AllItems)</p> <p>Folder (Common Views) </p> <p>Folder (Deferred Action)</p> <p>Folder (ExchangeSyncData) </p> <p>Folder (Finder) </p> <p>Folder (Freebusy Data)</p> <p>Folder (RCA_EWSSyncTestFolder) </p> <p>Folder (Recoverable Items) </p> <p>Folder (Deletions) </p> <p>Folder (Purges) </p> <p>Folder (Versions) </p> <p>Folder (Reminders) </p> <p>Folder (Schedule) </p> <p>Messages (Sharing) </p> <p>Folder (Shortcuts) </p> <p>Folder (Spooler Queue) </p> <p>Folder (System) </p> <p>Tasks (To-Do Search) </p> <p>Folder (Top of Information Store) </p> <p>Calendar (Calendar) </p> <p>Contacts (Contacts) </p> <p>Folder (Conversation Action Settings) </p> <p>Messages (Deleted Items) </p> <p>Folder (Spam) </p> <p>Messages (Drafts) </p> <p>Messages (Inbox) </p> <p>Messages (Archive) </p> <p>Folder (Suspected Spam) </p> <p>Folder (Journal) </p> <p>Messages (Junk E-Mail) </p> <p>Folder (Notes) </p> <p>Messages (Outbox) </p> <p>Folder (Quick Step Settings) </p> <p>Folder (RSS Feeds) </p> <p>Messages (Sent Items) </p> <p>Messages (Sync Issues) </p> <p>Messages (Conflicts) </p> <p>Messages (Local Failures) </p> <p>Messages (Server Failures) </p> <p>Tasks (Tasks) </p> <p>Folder (Transport Queue)</p> <p>Folder (Views)</p> </blockquote> <p>来源:<code>https://stackoverflow.com/questions/44958544/python-exchangelib-how-to-access-shared-public-folders-and-calendars</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/exchangewebservices" hreflang="zh-hans">exchangewebservices</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Tue, 10 Dec 2019 03:42:23 +0000 烂漫一生 2094316 at https://www.e-learn.cn Read emails and download attachment from Microsoft Exchange Server https://www.e-learn.cn/topic/1990172 <span>Read emails and download attachment from Microsoft Exchange Server</span> <span><span lang="" about="/user/231" typeof="schema:Person" property="schema:name" datatype="">安稳与你</span></span> <span>2019-12-08 09:31:23</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h3>问题</h3><br /><p>connect-to-exchange-mailbox-with-python/3072491....I have refereed the following link to connect to Exchange Online and download attachments and read mails on windows(using Python and exchangelib library). Now I want to accomplish the same task on CentOS but when I manually download the <code>exchangelib</code> library and install it. Whenever I try to import exchangelib, it throws an error like:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "exchangelib/__init__.py", line 2, in &lt;module&gt; from .account import Account # noqa File "exchangelib/account.py", line 8, in &lt;module&gt; from cached_property import threaded_cached_property ImportError: No module named cached_property </code></pre> <p>What might be the problem?</p> <p>My main objective is to read emails and download them. No imap/pop3 server address is available. Is there an alternative to <code>exchangelib</code>?</p> <pre><code>from exchangelib import DELEGATE, Account, Credentials credentials = Credentials( username='MYWINDOMAIN\\myusername', password='topsecret' ) account = Account( primary_smtp_address='john@example.com', credentials=credentials, autodiscover=True, access_type=DELEGATE ) # Print first 100 inbox messages in reverse order for item in account.inbox.all().order_by('-datetime_received')[:100]: print(item.subject, item.body, item.attachments) </code></pre> <p>I have used this code in Windows. Help me out with Linux.</p> <br /><h3>回答1:</h3><br /><p>This is how you read all emails and store all attachments with <code>exchangelib</code>:</p> <pre><code>from exchangelib import ServiceAccount, Configuration, Account, DELEGATE import os from config import cfg credentials = ServiceAccount(username=cfg['imap_user'], password=cfg['imap_password']) config = Configuration(server=cfg['imap_server'], credentials=credentials) account = Account(primary_smtp_address=cfg['smtp_address'], config=config, autodiscover=False, access_type=DELEGATE) unread = account.inbox.filter() # returns all mails for msg in unread: print(msg) print("attachments ={}".format(msg.attachments)) print("conversation_id ={}".format(msg.conversation_id)) print("last_modified_time={}".format(msg.last_modified_time)) print("datetime_sent ={}".format(msg.datetime_sent)) print("sender ={}".format(msg.sender)) print("text_body={}".format(msg.text_body.encode('UTF-8'))) print("#" * 80) for attachment in msg.attachments: fpath = os.path.join(cfg['download_folder'], attachment.name) with open(fpath, 'wb') as f: f.write(attachment.content) </code></pre> <p>Related: How can I send an email with an attachment with Python and Microsoft Exchange?</p> <br /><br /><br /><h3>回答2:</h3><br /><p><code>exchangelib</code> depends on various 3rd party packages, so you can't just download and import the package. You need to install it using <code>pip</code> to get these packages installed automatically:</p> <pre><code>$ pip install exchangelib </code></pre> <br /><br /><p>来源:<code>https://stackoverflow.com/questions/43491673/read-emails-and-download-attachment-from-microsoft-exchange-server</code></p></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/smtp" hreflang="zh-hans">smtp</a></div> <div class="field--item"><a href="/tag/exchange-server" hreflang="zh-hans">exchange-server</a></div> <div class="field--item"><a href="/tag/email-attachments" hreflang="zh-hans">email-attachments</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Sun, 08 Dec 2019 01:31:23 +0000 安稳与你 1990172 at https://www.e-learn.cn Python/exchangelib - How to access shared public folders and calendars https://www.e-learn.cn/topic/1939753 <span>Python/exchangelib - How to access shared public folders and calendars</span> <span><span lang="" about="/user/67" typeof="schema:Person" property="schema:name" datatype="">孤人</span></span> <span>2019-12-07 19:25:30</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><div class="alert alert-danger" role="alert"> <p>How can I connect to a shared public folder using exchangelib?</p> <pre><code>from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \ EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Message, \ Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, \ HTMLBody, Build, Version credentials = Credentials(username='DOMAIN\\username', password='password') config = Configuration(server='server', credentials=credentials, auth_type=NTLM, verify_ssl=False) account = Account(primary_smtp_address='user@email.com', config=config, autodiscover=False, access_type=DELEGATE) for i in account.root.get_folders(): print(i) </code></pre> <p>When I run the code above I get the output shown below. I'm pretty sure none of these options correspond to a shared public folder.</p> <blockquote> <p>Folder (AllItems)</p> <p>Folder (Common Views) </p> <p>Folder (Deferred Action)</p> <p>Folder (ExchangeSyncData) </p> <p>Folder (Finder) </p> <p>Folder (Freebusy Data)</p> <p>Folder (RCA_EWSSyncTestFolder) </p> <p>Folder (Recoverable Items) </p> <p>Folder (Deletions) </p> <p>Folder (Purges) </p> <p>Folder (Versions) </p> <p>Folder (Reminders) </p> <p>Folder (Schedule) </p> <p>Messages (Sharing) </p> <p>Folder (Shortcuts) </p> <p>Folder (Spooler Queue) </p> <p>Folder (System) </p> <p>Tasks (To-Do Search) </p> <p>Folder (Top of Information Store) </p> <p>Calendar (Calendar) </p> <p>Contacts (Contacts) </p> <p>Folder (Conversation Action Settings) </p> <p>Messages (Deleted Items) </p> <p>Folder (Spam) </p> <p>Messages (Drafts) </p> <p>Messages (Inbox) </p> <p>Messages (Archive) </p> <p>Folder (Suspected Spam) </p> <p>Folder (Journal) </p> <p>Messages (Junk E-Mail) </p> <p>Folder (Notes) </p> <p>Messages (Outbox) </p> <p>Folder (Quick Step Settings) </p> <p>Folder (RSS Feeds) </p> <p>Messages (Sent Items) </p> <p>Messages (Sync Issues) </p> <p>Messages (Conflicts) </p> <p>Messages (Local Failures) </p> <p>Messages (Server Failures) </p> <p>Tasks (Tasks) </p> <p>Folder (Transport Queue)</p> <p>Folder (Views)</p> </blockquote> </div><div class="alert alert-warning" role="alert"><p>来源:<code>https://stackoverflow.com/questions/44958544/python-exchangelib-how-to-access-shared-public-folders-and-calendars</code></p></div></div> <div class="field field--name-field-tags field--type-entity-reference field--label-above"> <div class="field--label">标签</div> <div class="field--items"> <div class="field--item"><a href="/tag/python" hreflang="zh-hans">python</a></div> <div class="field--item"><a href="/tag/exchangewebservices" hreflang="zh-hans">exchangewebservices</a></div> <div class="field--item"><a href="/tag/exchangelib" hreflang="zh-hans">exchangelib</a></div> </div> </div> Sat, 07 Dec 2019 11:25:30 +0000 孤人 1939753 at https://www.e-learn.cn