From 564abcb371dbd0ac5fafa79d16f0e3f1ec7c9d6b Mon Sep 17 00:00:00 2001 From: Uthman Fatih Date: Sun, 12 Oct 2025 20:21:05 +0100 Subject: [PATCH] Finished mail script, now reads emails + sends over smtp and imap4_ssl --- services/mail.py | 81 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/services/mail.py b/services/mail.py index 1285303..799a28f 100644 --- a/services/mail.py +++ b/services/mail.py @@ -7,6 +7,10 @@ import smtplib from email.mime.text import MIMEText + +from imaplib import IMAP4_SSL +from email import message_from_bytes + from dotenv import load_dotenv from os import getenv from os.path import dirname, join @@ -21,6 +25,12 @@ SMTP_PORT = int(getenv("SMTP_PORT")) SMTP_USERNAME = getenv("SMTP_USERNAME") SMTP_PASSWORD = getenv("SMTP_PASSWORD") +# IMAP server settings +IMAP_SERVER = getenv("IMAP_SERVER") +IMAP_PORT = int(getenv("IMAP_PORT")) +IMAP_USERNAME = getenv("IMAP_USERNAME") +IMAP_PASSWORD = getenv("IMAP_PASSWORD") + def send_email(receiver_email, subject, body): sender_email = SMTP_USERNAME @@ -38,3 +48,74 @@ def send_email(receiver_email, subject, body): print("HTML email sent successfully!") except Exception as e: print(f"Failed to send email: {e}") + +def receive_emails(folder="INBOX", limit=50): + emails = {} + + try: + M = IMAP4_SSL(host=IMAP_SERVER, port=IMAP_PORT) + M.login(IMAP_USERNAME, IMAP_PASSWORD) + M.select(folder) + + # Get all message IDs + typ, data = M.search(None, 'ALL') + if typ != 'OK' or not data[0]: + print("No messages found.") + return emails + + all_ids = data[0].split() + last_ids = all_ids[-limit:] # Take only the last 'limit' messages + + for num in last_ids: + typ, msg_data = M.fetch(num, '(RFC822)') + if typ != 'OK': + print(f"Failed to fetch message {num}") + continue + + # Parse the email + msg = message_from_bytes(msg_data[0][1]) + msg_id = msg.get('Message-ID') or num.decode() + + # Extract headers + subject = msg.get('Subject', '') + sender = msg.get('From', '') + date = msg.get('Date', '') + + # Extract plain text and HTML + body_text = "" + body_html = "" + if msg.is_multipart(): + for part in msg.walk(): + content_type = part.get_content_type() + content_disposition = str(part.get("Content-Disposition")) + if "attachment" in content_disposition: + continue + payload = part.get_payload(decode=True) + if payload: + payload = payload.decode(errors="ignore") + if content_type == "text/plain": + body_text = payload + elif content_type == "text/html": + body_html = payload + else: + payload = msg.get_payload(decode=True) + if payload: + body_text = payload.decode(errors="ignore") + + emails[msg_id] = { + "subject": subject, + "from": sender, + "date": date, + "body_text": body_text, + "body_html": body_html + } + + M.close() + M.logout() + + except Exception as e: + print(f"Error receiving emails: {e}") + + return emails + +print(receive_emails())