File size: 1,480 Bytes
1b59ee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import imaplib
import smtplib
import email
from email.message import EmailMessage
import os

# Configuration (from env vars)
EMAIL_USER = os.getenv("EMAIL_USER")
EMAIL_PASS = os.getenv("EMAIL_PASS") # Use App Password!
IMAP_SERVER = os.getenv("IMAP_SERVER") # e.g., imap.gmail.com
SMTP_SERVER = os.getenv("SMTP_SERVER") # e.g., smtp.gmail.com

def list_emails(count=5):
    """Lists the most recent emails."""
    try:
        mail = imaplib.IMAP4_SSL(IMAP_SERVER)
        mail.login(EMAIL_USER, EMAIL_PASS)
        mail.select("inbox")
        _, data = mail.search(None, "ALL")
        ids = data[0].split()
        
        emails = []
        for i in ids[-count:]:
            _, msg_data = mail.fetch(i, "(RFC822)")
            msg = email.message_from_bytes(msg_data[0][1])
            emails.append(f"From: {msg['from']}, Subject: {msg['subject']}")
        mail.logout()
        return str(emails)
    except Exception as e:
        return f"Error listing emails: {str(e)}"

def send_email(to, subject, body):
    """Sends an email."""
    try:
        msg = EmailMessage()
        msg.set_content(body)
        msg['Subject'] = subject
        msg['From'] = EMAIL_USER
        msg['To'] = to
        
        server = smtplib.SMTP_SSL(SMTP_SERVER, 465)
        server.login(EMAIL_USER, EMAIL_PASS)
        server.send_message(msg)
        server.quit()
        return "Email sent successfully."
    except Exception as e:
        return f"Error sending email: {str(e)}"