user791793
user791793

Reputation: 701

How to delete emails using UID in imaplib python

I'm trying to delete emails by UID. It's a hotmail email account I'm accessing.

Here's what I'm doing:

1. Connect to Email

imap = imaplib.IMAP4_SSL('imap-mail.outlook.com')
imap.login('[email protected]', "password")

2. Get UID from emails

resp, _ = imap.select('Inbox')
mbox_response, msgnums = imap.search( None,'FROM', '[email protected]')

messages = [] #Appending UID to this dictionary

for num in msgnums[0].split():
    msg_uid = imap.fetch(num, 'UID')
    messages.append({'uid':imap.fetch(num, 'UID')})

3. Print UIDs

print(messages)

I get the following output:

[{
  'uid': ('OK', [b'1 (UID 111)']), 
  'uid': ('OK', [b'2 (UID 114)'])
}]

4. How do I delete?

How do I use these UIDs to delete the specific message?

I've tried this without success...

for m in messages:
    imap.store(m['uid'],'+X-GM-LABELS', '\\Trash')

I get the following error:

TypeError: can't concat tuple to bytes

Upvotes: -1

Views: 1702

Answers (1)

Vladimir
Vladimir

Reputation: 6716

from imap_tools import MailBox, A
with MailBox('imap.mail.com').login('[email protected]', 'pwd', 'INBOX/test') as mailbox:

    # DELETE all flagged messages from current folder (INBOX/test)
    mailbox.delete(mailbox.uids(A(flagged=True)))

    # DELETE messages with 'cat' word in its html from current folder
    mailbox.delete([msg.uid for msg in mailbox.fetch() if 'cat' in msg.html])

https://github.com/ikvk/imap_tools

Read lib docs for details

Upvotes: -3

Related Questions