如何使用ExchangeLib过滤或跳过收件箱中的会议回复?当前正在获取AttributeError

时间:2019-05-15 19:32:10

标签: python attributeerror exchangelib

我需要遍历我的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'对象没有属性'find'

这是回溯: Error traceback image

这使代码失败的收件箱消息:Meeting response

这是一条普通的收件箱消息,不会使代码失败:Normal message - not related to calendar item

您可能会发现有趣的其他信息: 如果我过滤掉不包括日历项目的项目,则不会出错,请参见下面的工作代码。但是,我不知道具体如何过滤会议响应。

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__包含或response_tag__包含

这是我为“ 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

1 个答案:

答案 0 :(得分:0)

事实证明这是exchangelib中的一个错误,该错误是由MessageReply类上重复的字段定义引起的。已在https://github.com/ecederstrand/exchangelib/commit/cc8590b5557585ecbb3319f9391e30ace2f411fa

中修复