-
-
Save jkirk/39dc64747a9d78accde49de2e8dbdc6d to your computer and use it in GitHub Desktop.
| #!/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: ")) |
@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.
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!
I assume that the search will be performed inside all the mailboxes. What about some improvement to specify the desired one to search into?