├── README.md └── main.py /README.md: -------------------------------------------------------------------------------- 1 | # Python-Email-Auto-Unsubscribe -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import imaplib 3 | import email 4 | import os 5 | from bs4 import BeautifulSoup 6 | import requests 7 | 8 | load_dotenv() 9 | 10 | username = os.getenv("EMAIL") 11 | password = os.getenv("PASSWORD") 12 | 13 | def connect_to_mail(): 14 | mail = imaplib.IMAP4_SSL("imap.gmail.com") 15 | mail.login(username, password) 16 | mail.select("inbox") 17 | return mail 18 | 19 | def extract_links_from_html(html_content): 20 | soup = BeautifulSoup(html_content, "html.parser") 21 | links = [link["href"] for link in soup.find_all("a", href=True) if "unsubscribe" in link["href"].lower()] 22 | return links 23 | 24 | def click_link(link): 25 | try: 26 | response = requests.get(link) 27 | if response.status_code == 200: 28 | print("Successfully visited", link) 29 | else: 30 | print("Failed to visit", link, "error code", response.status_code) 31 | except Exception as e: 32 | print("Error with", link, str(e)) 33 | 34 | def search_for_email(): 35 | mail = connect_to_mail() 36 | _, search_data = mail.search(None, '(BODY "unsubscribe")') 37 | data = search_data[0].split() 38 | 39 | links = [] 40 | 41 | for num in data: 42 | _, data = mail.fetch(num, "(RFC822)") 43 | msg = email.message_from_bytes(data[0][1]) 44 | 45 | if msg.is_multipart(): 46 | for part in msg.walk(): 47 | if part.get_content_type() == "text/html": 48 | html_content = part.get_payload(decode=True).decode() 49 | links.extend(extract_links_from_html(html_content)) 50 | else: 51 | content_type = msg.get_content_type() 52 | content = msg.get_payload(decode=True).decode() 53 | 54 | if content_type == "text/html": 55 | links.extend(extract_links_from_html(content)) 56 | 57 | mail.logout() 58 | return links 59 | 60 | def save_links(links): 61 | with open("links.txt", "w") as f: 62 | f.write("\n".join(links)) 63 | 64 | links = search_for_email() 65 | for link in links: 66 | click_link(link) 67 | 68 | save_links(links) --------------------------------------------------------------------------------