Reputation: 205
I want to delete an email from my Inbox using imaplib and gmail. The problem is that the email is moved from Inbox to All mail folder but I want it sent to Trash/Bin folder.
Sample code:
#!/usr/bin/env python
import imaplib
imap_host = 'imap.gmail.com'
imap_user = '[email protected]'
imap_pass = 'mypass'
imap = imaplib.IMAP4_SSL(imap_host)
imap.login(imap_user, imap_pass)
status, data = imap.select('INBOX')
status, mail_id = imap.search(None, '(SUBJECT "My subject")')
status, msg_header = imap.fetch(mail_id[0], '(BODY[TEXT])')
saveFile = open('sample.txt', 'w')
saveFile.write(str(msg_header))
saveFile.close()
print "Received email body!"
# Delete the email
print "Deleting the email..."
imap.store(mail_id[0], '+FLAGS', '\\Deleted')
imap.expunge()
print "Email deleted!"
I want to save the email body into a new file then delete that email (There will be only one email on this email address).
Upvotes: 4
Views: 4179
Reputation: 868
I know it's an old topic but i had the same problem and here my solution to move all the message in INBOX in gmail to the Trash
connection = imaplib.IMAP4_SSL('imap.gmail.com')
connection.login("[email protected]", "password")
connection.select(mailbox='"INBOX"', readonly=False)
connection.store("1:*", '+X-GM-LABELS', '\\Trash')
connection.close() # close and logout the connection
connection.logout()
Upvotes: 0
Reputation: 412
Gmail does not allow to delete emails directly from the INBOX.
They have mentioned complete email delete behaviour here https://support.google.com/mail/answer/78755?hl=en
In gmail imap store with delete flags works only for Trash and Spam.
imap.store(mail_id[0], '+FLAGS', '\Deleted')
It seems they made it intentionally for avoiding accidental deletes from the Inbox and custom folders.
If you want to delete email from Inbox or custom folders you need to apply Trash label to the email like this
. STORE 1 +X-GM-LABELS (\Trash)
Upvotes: 1