pythonemailgmailimapimaplib

Mark as unseen on Gmail (imaplib)


I'm trying to mark email as unseen on Gmail server.

I'm using this command:

res, data = mailbox.uid('STORE', uid, '-FLAGS', '(\Seen)')

Everything goes OK but when I check it using web browser it's still marked as seen. When I check flags here's what I got:

 b'46 (FLAGS (-FLAGS \\Seen))'

I've seen multiple questions on this issue but none of the proposed solutions work.

Just to mention that I'm appending this email using:

mailbox.append(db_email.folder, "-FLAGS \Seen", time.mktime(db_email.date.timetuple()), mail.as_bytes())

But the flag parameter -FLAGS \Seen does not have any effect since it's the same when I don't pass flag argument.

Also, I've double-checked uid for given mail folder and it matches to appropriate email.


Solution

  • It appears you've misunderstood flags on APPEND a bit.

    By doing APPEND folder (-FLAGS \Seen) ... you've actually created a message with two flags: The standard \Seen flag, and a nonstandard -FLAGS flag.

    To create a message without the \Seen flag, just use () as your flag list for APPEND.

    -FLAGS is a subcommand to STORE, saying to remove these flags from the current list. Conversely, +FLAGS is add these flags to the current list. The plain FLAGS overwrites the current list.

    Also, if you do remove the \Seen flag over an IMAP connection, it can take sometime to show up in the GMail WebUI. You may need to refresh or switch folders to get the changes to render.

    NB: You are not protecting your backslashes. \S is not a legal escape sequence, so will be passed through, but you should either use a double backslash ('\\Seen') or a raw string (r'\Seen')