Finished mail script, now reads emails + sends over smtp and imap4_ssl

This commit is contained in:
Uthman Fatih 2025-10-12 20:21:05 +01:00
parent cb22c6b6ba
commit 564abcb371

View File

@ -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())