Python 3: Move email to trash by uid (imaplib)

Question:

I want to move an email from my inbox to the trash folder, I do not want the email permanently deleted, I want it to go through the process of waiting 30 days in the trash to be permanently deleted.

1.Logged in:

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login("[email protected]", "example")

2.Got the list of uids in my inbox:

mail.select("inbox")
result, data = mail.uid('search', None, "ALL")
uidList = data[0].split()

3.Processed these emails:

#processEmails returns the uids of the emails that I need
#not really important for the purposes of this question

newUidList = processEmails(uidList)

4.Delete the emails in the newUidList

for uid in newUidList:
    mail.uid('STORE',uid, '+FLAGS', '(\Deleted)')

I thought that this line mail.uid('STORE',uid, '+FLAGS', '(\Deleted)') would solve the problem (because that’s what I found on the internet). But being here asking this question, you probably have correctly guessed that it did not.

What was happening?

When I executed this script, the emails disappeared from the inbox just as planned. But when I visit the trash folder, there is nothing there. So I thought maybe they were permanently deleted.

But they were not. I noticed this when I saw that my email storage space is filling up quick which means my emails were still there somewhere.

I go into the “All Emails” folder and there they are.

So my question is…

  1. How do I get the result I want? Which is moving the emails to the trash folder by their UIDs.
  2. Why is it not doing what I thought it would do? I am asking for an explanation for this line mail.uid('STORE',uid, '+FLAGS', '(\Deleted)')

And most importantly…

Thank you for your input 🙂

Asked By: 0_jump

||

Answers:

I found the answer!

So for anyone having the same problem, I found out how to move your email to the trash by uid. referring back to my post, I should have put mail.uid('STORE', uid, '+X-GM-LABELS', '\Trash') instead of mail.uid('STORE',uid, '+FLAGS', '(\Deleted)')

And there you have it 🙂

Answered By: 0_jump
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.