简体   繁体   中英

How can I move an email message from All mail to Trash using imaplib and gmail

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 = 'myemail@gmail.com'
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).

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)

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("xxxxx@gmail.com", "password")
connection.select(mailbox='"INBOX"', readonly=False)
connection.store("1:*", '+X-GM-LABELS', '\\Trash')
connection.close()  # close and logout the connection
connection.logout()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM