1

我需要遍历 Outlook 收件箱中的电子邮件并获取主题、发件人和日期等属性。但是,每当我在收件箱中遇到日历会议响应时,我都会收到一个 AttributeError(我无法使用异常处理来捕获)。错误消息是“'NoneType' 对象没有属性 'find'”。我正在使用 Python 3.6 版和 ExchangeLib 1.12.4。

根据https://github.com/ecederstrand/exchangelib/blob/master/README.md,我应该能够做到这一点:

for item in account.inbox.all().order_by('-datetime_received')[:5]:
    if isinstance(item, MeetingResponse):
       do_something

但是我下面的代码无法识别该项目是一个 MeetingResponse 并在它得到一个会议响应时立即抛出一个 AttributeError


from exchangelib import DELEGATE, Account, Credentials, Configuration, CalendarItem, EWSDateTime
from exchangelib.items import MeetingRequest, MeetingCancellation, MeetingResponse

...

for item in account.inbox.all().order_by('-datetime_received')[:100]:
    if isinstance(item, MeetingResponse):
        print('its a meeting response')
        continue
    else:
        subj= item.subject
        senderName = item.sender.name
        senderEmail = item.sender.email_address
        year = item.datetime_received.year
        month = item.datetime_received.month
        day = item.datetime_received.day
        df=df.append({'Subject': subj, 'SenderName':senderName, 'SenderEmail':senderEmail,'Year': year, 'Month':month, 'Day': day}, ignore_index=True)

我尝试过的其他不起作用的事情,包括这样的异常处理:

       try:
            subj= item.subject
            senderName = item.sender.name
            senderEmail = item.sender.email_address
            year = item.datetime_received.year
            month = item.datetime_received.month
            day = item.datetime_received.day
            df=df.append({'Subject': subj, 'SenderName':senderName, 'SenderEmail':senderEmail,'Year': year, 'Month':month, 'Day': day}, ignore_index=True)
            #print(sender)
        except Exception as e:
            print(e)

并检查消息类型,如下所示:Python exchangelib: check if item is a message or not

但是,无论如何,我总是得到同样的错误: AttributeError: 'NoneType' object has no attribute 'find'

这是回溯: 错误回溯图像

这是使代码失败的收件箱消息:会议响应

这是一条正常的收件箱消息,不会使代码失败:正常消息 - 与日历项目无关

您可能会感兴趣的其他信息:如果我过滤掉意味着日历项目不包括在内的项目,我不会收到任何错误,请参阅下面的工作代码。但是,我不知道具体如何过滤会议响应。

for item in account.inbox.filter(subject__contains='Lexis')[:10]:
    print(item.subject)

但是,下面的代码不起作用并抛出相同的 AttributeError

for item in account.inbox.filter(subject__contains='Accepted:')[:10]:
    print(item.subject)

它不允许我使用 ELEMENT_NAME__contains 或 response_tag__contains 进行过滤

这是我在运行“for item in account.inbox.filter(subject__contains='Accepted:')[:1]:...”时得到的部分 xml

DEBUG:exchangelib.queryset:Initializing cache DEBUG:exchangelib.folders:Finding [Inbox(Root(
<exchangelib.account.Account object at 0x0000000B4EA97278>, 
...
Response time: 0.39099999982863665 Status code: 200 Request headers: {'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'Keep-Alive', 'Content-Type': 'text/xml;
      charset=utf-8', 'Cookie': 'delted'; ClientId=FTNTNFBGUKKHMWERGKW; exchangecookie=deleted', 'Content-Length': '1060', 'Authorization': deleted} Response headers: {'Cache-Control': 'private', 'Transfer-Encoding': 'chunked', 'Content-Type': 'text/xml;
      charset=utf-8', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Server': 'Microsoft-IIS/8.5', 'request-id': 'ed9787e2-b43e-4df5-bf8b-a2d91a0f4b6c', 'X-CalculatedBETarget': 'ex2.parent_company.local', 'X-DiagInfo': 'EX2', 'X-BEServer': 'EX2',
      'X-AspNet-Version': '4.0.30319', 'Set-Cookie': deleted; expires=Sat, 15-Jun-2019 14:06:36 GMT; path=/EWS; secure; HttpOnly', 'Persistent-Auth': 'true', 'X-Powered-By': 'ASP.NET', 'X-FEServer': 'EX2', 'Date': 'Thu, 16 May 2019 14:06:36 GMT'} Request
      data: b'
      <?xml version=\'1.0\' encoding=\'utf-8\'?>\n
      <s:Envelope xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
        <s:Header>
          <t:RequestServerVersion Version="Exchange2013_SP1" />
          <t:TimeZoneContext>
            <t:TimeZoneDefinition Id="Eastern Standard Time" /></t:TimeZoneContext>
        </s:Header>
        <s:Body>
          <m:FindItem Traversal="Shallow">
            <m:ItemShape>
              <t:BaseShape>IdOnly</t:BaseShape>
            </m:ItemShape>
            <m:IndexedPageItemView BasePoint="Beginning" MaxEntriesReturned="1" Offset="0" />
            <m:Restriction>
              <t:Contains ContainmentComparison="Exact" ContainmentMode="Substring">
                <t:FieldURI FieldURI="item:Subject" />
                <t:Constant Value="Accepted:" /></t:Contains>
            </m:Restriction>
            <m:ParentFolderIds>
              <t:DistinguishedFolderId Id="inbox">
                <t:Mailbox>
                  <t:EmailAddress>my_user_name@co_name.com</t:EmailAddress>
                  <t:RoutingType>SMTP</t:RoutingType>
                  <t:MailboxType>Mailbox</t:MailboxType>
                </t:Mailbox>
              </t:DistinguishedFolderId>
            </m:ParentFolderIds>
          </m:FindItem>
        </s:Body>
      </s:Envelope>' Response data: b'
      <?xml version="1.0" encoding="utf-8"?>
      <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
          <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1473" MinorBuildNumber="3" Version="V2_23" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <m:FindItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <m:ResponseMessages>
              <m:FindItemResponseMessage ResponseClass="Success">
                <m:ResponseCode>NoError</m:ResponseCode>
                <m:RootFolder IndexedPagingOffset="1" TotalItemsInView="23" IncludesLastItemInRange="false">
                  <t:Items>
                    <t:MeetingResponse>
                      <t:ItemId Id=deleted/></t:MeetingResponse>
                  </t:Items>
                </m:RootFolder>
              </m:FindItemResponseMessage>
            </m:ResponseMessages>
          </m:FindItemResponse>
        </s:Body>
      </s:Envelope>' 
 DEBUG:exchangelib.util:Session 27048 thread 16144: Useful response from https://cloudmail.firm_name.com/EWS/Exchange.asmx 
 ...
 Response time: 0.06199999991804361 Status code: 200 
 Request headers: {'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'Keep-Alive', 'Content-Type': 'text/xml;
          charset=utf-8', 'Cookie': delted; ClientId=deleted; exchangecookie=efc27b1d76ad4fea808e577a4e34aa30', 'Content-Length': '5290'} Response headers: {'Cache-Control': 'private', 'Transfer-Encoding': 'chunked', 'Content-Type': 'text/xml; charset=utf-8',
          'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Server': 'Microsoft-IIS/8.5', 'request-id': '7bbb3dee-e6f0-42d2-8e0c-dd296e02c27a', 'X-CalculatedBETarget': 'ex2.parent_company.local', 'X-DiagInfo': 'EX2', 'X-BEServer': 'EX2', 'X-AspNet-Version':
          '4.0.30319', 'Set-Cookie': 'exchangecookie=efc27b1d76ad4fea808e577a4e34aa30; path=/, X-BackEndCookie=S-1-5-21-3493326517-1059625486-1703856831-1754=u56Lnp2ejJqBy5nIx5yeyM/Sys/NyNLLy8rL0saczZnSycqZnJ3HzsudyM/MgYHNz87G0s/J0s7Kq87Lxc/JxczI; expires=Sat,
          15-Jun-2019 14:06:37 GMT; path=/EWS; secure; HttpOnly', 'X-Powered-By': 'ASP.NET', 'X-FEServer': 'EX2', 'Date': 'Thu, 16 May 2019 14:06:36 GMT'} Request data: b'
          <?xml version=\'1.0\' encoding=\'utf-8\'?>\n
          <s:Envelope xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <s:Header>
              <t:RequestServerVersion Version="Exchange2013_SP1" />
              <t:TimeZoneContext>
                <t:TimeZoneDefinition Id="Eastern Standard Time" /></t:TimeZoneContext>
            </s:Header>
            <s:Body>
              <m:GetItem>
                <m:ItemShape>
                  <t:BaseShape>IdOnly</t:BaseShape>
                  <t:AdditionalProperties>
                    <t:FieldURI FieldURI="calendar:EndTimeZone" />
                    <t:FieldURI FieldURI="calendar:EndTimeZone" />
                    <t:FieldURI FieldURI="calendar:StartTimeZone" />
                    <t:FieldURI FieldURI="calendar:StartTimeZone" />
                    <t:FieldURI FieldURI="calendar:AdjacentMeetingCount" />
                    <t:FieldURI FieldURI="calendar:AllowNewTimeProposal" />
                    <t:FieldURI FieldURI="calendar:AppointmentReplyTime" />
                    <t:FieldURI FieldURI="calendar:AppointmentSequenceNumber" />
                    <t:FieldURI FieldURI="meeting:AssociatedCalendarItemId" />
                    <t:FieldURI FieldURI="item:Attachments" />
                    <t:FieldURI FieldURI="message:From" />
                    <t:FieldURI FieldURI="message:BccRecipients" />
                    <t:FieldURI FieldURI="item:Body" />
                    <t:FieldURI FieldURI="item:Categories" />
                    <t:FieldURI FieldURI="message:CcRecipients" />
                    <t:FieldURI FieldURI="calendar:ConferenceType" />
                    <t:FieldURI FieldURI="calendar:ConflictingMeetingCount" />
                    <t:FieldURI FieldURI="item:ConversationId" />
                    <t:FieldURI FieldURI="message:ConversationIndex" />
                    <t:FieldURI FieldURI="message:ConversationTopic" />
                    deleted remaining
                    /></t:AdditionalProperties>
                </m:ItemShape>
             
              </m:GetItem>
            </s:Body>
          </s:Envelope>' Response data: b'
          <?xml version="1.0" encoding="utf-8"?>
          <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
            <s:Header>
              <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1473" MinorBuildNumber="3" Version="V2_23" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
            </s:Header>
            <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
              <m:GetItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
                <m:ResponseMessages>
                  <m:GetItemResponseMessage ResponseClass="Success">
                    <m:ResponseCode>NoError</m:ResponseCode>
                    <m:Items>
                      <t:MeetingResponse>
                        <t:MimeContent CharacterSet="UTF-8">+deleted_to_save_space==</t:MimeContent>
                        <t:ItemId deleted/><t:ItemClass>IPM.Schedule.Meeting.Resp.Pos</t:ItemClass><t:Subject>Accepted: I need a meeting request response in my inbox for debugging</t:Subject><t:Sensitivity>Normal</t:Sensitivity><t:Body BodyType=" HTML
                          " IsTruncated="false "> deleted </t:Body><t:DateTimeReceived>2019-05-15T13:49:30-04:00</t:DateTimeReceived><t:Size>10767</t:Size><t:Importance>Normal</t:Importance><t:IsSubmitted>false</t:IsSubmitted><t:IsDraft>false</t:IsDraft><t:IsFromMe>false</t:IsFromMe><t:IsResend>false</t:IsResend><t:IsUnmodified>true</t:IsUnmodified><t:InternetMessageHeaders><t:InternetMessageHeader HeaderName="Received
                          ">from ex1.parent_company.local (10.0.36.13) by ex2.parent_company.local (10.0.36.14) with Microsoft SMTP Server (TLS) id 15.0.1473.3 via Mailbox Transport; Wed, 15 May 2019 13:49:29 -0400</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Received
                          ">from ex2.parent_company.local (10.0.36.14) by EX1.parent_company.local (10.0.36.13) with Microsoft SMTP Server (TLS) id 15.0.1473.3; Wed, 15 May 2019 13:49:29 -0400</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Received
                          ">from ex2.parent_company.local ([fe80::69e0:8dd2:36c7:ee74]) by EX2.parent_company.local ([fe80::69e0:8dd2:36c7:ee74%12]) with mapi id 15.00.1473.003; Wed, 15 May 2019 13:49:29 -0400</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Content-Type ">application/ms-tnef</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Content-Transfer-Encoding ">binary</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Subject
                          ">Accepted: I need a meeting request response in my inbox for debugging</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Thread-Topic ">I need a meeting request response in my inbox for debugging</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Thread-Index
                          ">AdULRnbwosyAOWPxSuSGj1JtvGTLdAAAAliAAAACz/A=</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Date ">Wed, 15 May 2019 13:49:29 -0400</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Message-ID
                          ">&lt;9d0c3918cd1843778df749ee247fe4dd@EX2.parent_company.local&gt;</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Accept-Language ">en-CA, en-US</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Content-Language ">en-US</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-Exchange-Organization-SCL
                          ">-1</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-TNEF-Correlator ">&lt;9d0c3918cd1843778df749ee247fe4dd@EX2.parent_company.local&gt;</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="MIME-Version
                          ">1.0</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-Exchange-Transport-FromEntityHeader ">Hosted</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-Exchange-Organization-MessageDirectionality
                          ">Originating</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-Exchange-Organization-AuthSource ">EX2.parent_company.local</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-Exchange-Organization-AuthAs
                          ">Internal</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-Exchange-Organization-AuthMechanism ">03</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-Originating-IP ">[10.0.36.38]</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-Exchange-Organization-Network-Message-Id
                          ">ef6a25be-a08a-4029-28c0-08d6d95dae26</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="Return-Path ">SKim@co_name.com</t:InternetMessageHeader><t:InternetMessageHeader HeaderName="X-MS-Exchange-Organization-AVStamp-Enterprise
                          ">1.0</t:InternetMessageHeader></t:InternetMessageHeaders><t:DateTimeSent>2019-05-15T13:49:29-04:00</t:DateTimeSent><t:DateTimeCreated>2019-05-15T13:49:30-04:00</t:DateTimeCreated>deleted...<t:LastModifiedTime>2019-05-15T13:49:34-04:00</t:LastModifiedTime><t:IsAssociated>false</t:IsAssociated><t:WebClientReadFormQueryString>deleted</t:WebClientReadFormQueryString><t:ConversationId Id=deleted/><t:UniqueBody BodyType=" HTML " IsTruncated="false ">&lt;html&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;</t:UniqueBody><t:TextBody BodyType="Text
                          " IsTruncated="false
                          ">&#xD;\n</t:TextBody><t:Sender><t:Mailbox><t:Name>Name</t:Name><t:EmailAddress>name@co_name.com</t:EmailAddress><t:RoutingType>SMTP</t:RoutingType><t:MailboxType>Mailbox</t:MailboxType></t:Mailbox></t:Sender><t:ToRecipients><t:Mailbox><t:Name>My Full Name</t:Name><t:EmailAddress>my_user_name@co_name.com</t:EmailAddress><t:RoutingType>SMTP</t:RoutingType><t:MailboxType>Mailbox</t:MailboxType></t:Mailbox></t:ToRecipients><t:IsReadReceiptRequested>false</t:IsReadReceiptRequested><t:IsDeliveryReceiptRequested>false</t:IsDeliveryReceiptRequested><t:ConversationIndex>AdULRnbwosyAOWPxSuSGj1JtvGTLdAAAAliAAAAC6g8=</t:ConversationIndex><t:ConversationTopic>I need a meeting request response in my inbox for debugging</t:ConversationTopic><t:From><t:Mailbox><t:Name>name</t:Name><t:EmailAddress>name@co_name.com</t:EmailAddress><t:RoutingType>SMTP</t:RoutingType><t:MailboxType>Mailbox</t:MailboxType></t:Mailbox></t:From><t:InternetMessageId>delted</t:InternetMessageId><t:IsRead>true</t:IsRead><t:ReceivedBy><t:Mailbox><t:Name>My Full Name</t:Name><t:EmailAddress>my_user_name@co_name.com</t:EmailAddress><t:RoutingType>SMTP</t:RoutingType><t:MailboxType>Mailbox</t:MailboxType></t:Mailbox></t:ReceivedBy><t:ReceivedRepresenting><t:Mailbox><t:Name>My Full Name</t:Name><t:EmailAddress>my_user_name@co_name.com</t:EmailAddress><t:RoutingType>SMTP</t:RoutingType><t:MailboxType>Mailbox</t:MailboxType></t:Mailbox></t:ReceivedRepresenting><t:AssociatedCalendarItemId Id=deleted/><t:IsDelegated>false</t:IsDelegated><t:IsOutOfDate>false</t:IsOutOfDate><t:HasBeenProcessed>true</t:HasBeenProcessed><t:ResponseType>Accept</t:ResponseType><t:Start>2019-05-15T14:00:00-04:00</t:Start><t:End>2019-05-15T14:30:00-04:00</t:End><t:Location/><t:CalendarItemType>Single</t:CalendarItemType></t:MeetingResponse></m:Items></m:GetItemResponseMessage></m:ResponseMessages></m:GetItemResponse></s:Body></s:Envelope>'

DEBUG:exchangelib.util:Session 27048 thread 2440: Useful response from https://cloudmail.firm_name.com/EWS/Exchange.asmx
DEBUG:exchangelib.protocol:Server cloudmail.firm_name.com: Releasing session 27048
DEBUG:exchangelib.services:GetItem._get_elements result 1 of 1 is ready

4

1 回答 1

0

事实证明,这是由于MessageReply类上的重复字段定义导致的 exchangelib 中的错误。在https://github.com/ecederstrand/exchangelib/commit/cc8590b5557585ecbb3319f9391e30ace2f411fa中修复

于 2019-05-20T09:23:08.077 回答