Last active
November 22, 2022 13:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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: ")) |
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')
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
@SopalajodeArrierez: sorry, I did not get any notifications on your comment on this gist (because I did not star my own gist. doh).
But no, the default folder which is defined by
imapserver.select()
is'INBOX'
. The search is then performed (only) in that folder (I do not know how to search within any subfolders, I assume one has to iterate over all folders and perform a search within each folder).This script was quickly hacked just to answer your question @ StackExchange / Unix & Linux. There are no plans for improvement, but I will happily accept any change requests (although gist does not seem to support PRs). But nevertheless: adding an option to search within a specific folder should not be that hard.