forked from x4nth055/pythoncode-tutorials
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete_emails.py
More file actions
Latest commit
49 lines (47 loc) · 1.82 KB
/
Copy pathdelete_emails.py
File metadata and controls
49 lines (47 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
importimaplib
importemail
fromemail.headerimportdecode_header
# account credentials
username="youremailaddress@provider.com"
password="yourpassword"
# create an IMAP4 class with SSL
imap=imaplib.IMAP4_SSL("imap.gmail.com")
# authenticate
imap.login(username, password)
# select the mailbox I want to delete in
# if you want SPAM, use imap.select("SPAM") instead
imap.select("INBOX")
# search for specific mails by sender
status, messages=imap.search(None, 'FROM "googlealerts-noreply@google.com"')
# to get all mails
# status, messages = imap.search(None, "ALL")
# to get mails by subject
# status, messages = imap.search(None, 'SUBJECT "Thanks for Subscribing to our Newsletter !"')
# to get mails after a specific date
# status, messages = imap.search(None, 'SINCE "01-JAN-2020"')
# to get mails before a specific date
# status, messages = imap.search(None, 'BEFORE "01-JAN-2020"')
# convert messages to a list of email IDs
messages=messages[0].split(b' ')
formailinmessages:
_, msg=imap.fetch(mail, "(RFC822)")
# you can delete the for loop for performance if you have a long list of emails
# because it is only for printing the SUBJECT of target email to delete
forresponseinmsg:
ifisinstance(response, tuple):
msg=email.message_from_bytes(response[1])
# decode the email subject
subject=decode_header(msg["Subject"])[0][0]
ifisinstance(subject, bytes):
# if it's a bytes type, decode to str
subject=subject.decode()
print("Deleting", subject)
# mark the mail as deleted
imap.store(mail, "+FLAGS", "\\Deleted")
# permanently remove mails that are marked as deleted
# from the selected mailbox (in this case, INBOX)
imap.expunge()
# close the mailbox
imap.close()
# logout from the account
imap.logout()