0

I am trying to read and save the most recent email attachments with specific email subject. I know how to filter the email by the subject line OR the receive time. But I don't know how to combine this two requests. Can you please let me know if you have a better idea to resolve this?

I only know how to read the most recent email using this

for item in a.inbox.children:
    for e in item.all().order_by('-datetime_received')[:1]:
        for attachment in e.attachments:
             ...

I know how to get the specific subject email:

for item in a.inbox.children.filter(subject = 'this is my subject line'):
    for attachment in item.attachments:
          ....

How could I obtain the most recent email attachment from a specific subject line?

Thanks a lot!

j.y
  • 1

1 Answers1

0

I'm not sure what you mean by "most recent attachment", but attachments do have a last_modified_time field: https://github.com/ecederstrand/exchangelib/blob/a695bda1edd9a574532bd099fe0c19968a5c5be4/exchangelib/attachments.py#L42

So you can do something like:

last_modified_attachment = sorted(
    item.attachments, 
    key=lambda i: i.last_modified_time
)[-1]

For each item in your search, this would select the attachment that was last modified. But you may find that they were all modified at almost the same time, if last_modified_time means the time when the attachment was created in EWS.

For item attachments (attachments of type ItemAttachment), you could also dig into one of the datetime fields on attachment.item and sort by one of those.

Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
  • Thanks Erik! Most recent means the first email order by the newest receive date. order_by('-datetime_received')[:1] – j.y Jan 23 '20 at 15:11