The below code is my understanding of how one might go about deleting an email using imaplib. It includes moving the email to the 'trash' before deletion which, I believe, is a requirement when using gmail.
However as you can see I appear to be falling at the label modifying stage. I've viewed other similar topics here on stack and despite attempting multiple suggested solutions, I have not been able to resolve this.
>>> import imaplib
>>> server = imaplib.IMAP4_SSL(GMAIL_IMAP)
>>> server.login(EMAIL, PASSWORD)
('OK', [b'[email protected] authenticated (Success)'])
>>> server.select("INBOX")
('OK', [b'17'])
>>> status, uids = server.uid("search", None, "ALL")
>>> uids
[b'1 2 3 4 5 6 7 8 9 10 15 16 17 18 19 43 44']
uids = [uid for uid in uids[0].split()]
>>> uids
[b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'10', b'15', b'16', b'17', b'18', b'19', b'43', b'44']
>>> server.store(uids[-1], "X-GM-LABELS", "\\Trash")
('OK', [None])
>>> server.store(uids[-1], "+FLAGS", "\\Deleted")
('OK', [None])
>>> server.expunge()
('OK', [None])
>>> server.close()
('OK', [b'Returned to authenticated state. (Success)'])
>>> server.logout()
('BYE', [b'LOGOUT Requested'])
You are mixing UIDs and sequence numbers.
You ask for a UID SEARCH, so get UIDs back. You need to use UID STORE as well:
And so on for the other store commands. On Gmail only, when you move it to the trash this way, you don't need to bother with the \Deleted and Expunge commands. The server should do that automatically for you.