2

I'd like to mark an email as read from my python code. I'm using

from exchangelib import Credentials, Account
my_account = Account(...)
credentials = Credentials(...)

to get access to the account. This part works great. I then get into my desired folder using this

var1 = my_account.root / 'branch1' / 'desiredFolder'

Again, this works great. This is where marking it as read seems to not work.

item = var1.filter(is_read=False).values('body')
for i, body in enumerate(item):
   #Code doing stuff
   var1.filter(is_read=False)[i].is_read = True
   var1.filter(is_read=False)[i].save(updated_fields=['is_read'])

I've tried the tips and answers from this post Mark email as read with exchangelib, but the emails still show as unread. What am I doing wrong?

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45

2 Answers2

5

I think you the last line of code that you save() do not work as you think that after you set is_read of unread[i] element to True, this unread[i] of course not appear in var1.filter(is_read=False)[i] again, so you acttually did not save this.
I think this will work.

for msg in my_account.inbox.filter(is_read=False):
    msg.is_read = True
    msg.save(updated_fields=['is_read'])
thangnd
  • 101
  • 3
  • 1
    This should work and is the recommended approach. If you are checking the read status of the email afterwards in e.g. Outlook or OWA, then be aware that these clients are sometimes slow in updating their cache, so it may take a while for the change to appear. – Erik Cederstrand Aug 03 '22 at 05:19
3

To expand on @thangnd's answer, the reason your code doesn't work is that you are calling .save() on a different Python object than the object you are setting the is_read flag on. Every time you call var1.filter(is_read=False)[i], a new query is sent to the server, and a new Python object is created.

Additionally, since you didn't specify a sort order (and new emails may be incoming while the code is running), you may not even be hitting the same email each time you call var1.filter(is_read=False)[i].

Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63