122 lines
3.7 KiB
Python
122 lines
3.7 KiB
Python
# _ __________________
|
|
# | | / / _/ ____/ _/ /
|
|
# | | / // // / __ / // /
|
|
# | |/ // // /_/ // // /___
|
|
# |___/___/\____/___/_____/
|
|
# © Uthmn 2025 under MIT license
|
|
|
|
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
|
|
|
|
# Load environment variables from .env file
|
|
dotenv_path = join(dirname(__file__), "../.env")
|
|
load_dotenv(dotenv_path)
|
|
|
|
# SMTP server settings
|
|
SMTP_SERVER = getenv("SMTP_SERVER")
|
|
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
|
|
|
|
# Create the email
|
|
message = MIMEText(body, "html")
|
|
message["Subject"] = subject
|
|
message["From"] = sender_email
|
|
message["To"] = receiver_email
|
|
|
|
# Connect using SSL
|
|
try:
|
|
with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
|
|
server.login(SMTP_USERNAME, SMTP_PASSWORD)
|
|
server.sendmail(sender_email, receiver_email, message.as_string())
|
|
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())
|