Skip to content

Instantly share code, notes, and snippets.

@jkirk
Last active November 22, 2022 13:28
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkirk/39dc64747a9d78accde49de2e8dbdc6d to your computer and use it in GitHub Desktop.
Save jkirk/39dc64747a9d78accde49de2e8dbdc6d to your computer and use it in GitHub Desktop.
List (or flag) mails of an IMAP account which contains a given subject text
#!/usr/bin/python3
import getpass
def del_imap(server, port, login, password, search):
import imaplib, email
# NOTE: According to RFC 1730 the SEARCH commands searches for 'messages that
# CONTAIN the specified string. When multiple keys are specified, the result
# is the intersection (AND function) of all the messages that match those
# keys.
# _search_command = '(FROM ' + search + ')'
# _search_command = '(SUBJECT "testmail" FROM ' + search + ')'
_search_command = '(SUBJECT ' + search + ')'
imapserver = imaplib.IMAP4_SSL(server, port)
imapserver.login(login, password)
imapserver.select()
typ, data = imapserver.search(None, _search_command)
if data[0]:
for num in data[0].split():
typ, data = imapserver.fetch(num, '(RFC822.HEADER)')
print (data[0][1].decode())
# Uncomment the following line if the listed files should also be
# flagged for deletion
#imapserver.store(num, '+FLAGS', '\\Deleted')
imapserver.close()
imapserver.logout()
del_imap(input("IMAP Server: "), 993, input("Username: "), getpass.getpass(), input("Search: "))
@redlegoman
Copy link

I changed this bit so it didn't melt down if the search was empty:

    typ, data = imapserver.search(None, _search_command)
    if data[0]:
      for num in data[0].split():
          typ, data = imapserver.fetch(num, '(RFC822.HEADER)')
          print (data[0][1].decode())
          # Uncomment the following line if the listed files should also be
          # flagged for deletion
          #imapserver.store(num, '+FLAGS', '\\Deleted')

@jkirk
Copy link
Author

jkirk commented Aug 15, 2022

Oh, thanks @redlegoman!

Although I could not test the fix, it LGFM, so I just updated the gist. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment