vrn123/workplace-decision-engine
0
1import imaplib2import email3import os4 5 6EMAIL = os.getenv("EMAIL_USER")7PASSWORD = os.getenv("EMAIL_PASS")8 9 10def fetch_unread_emails():11 emails = []12 13 try:14 mail = imaplib.IMAP4_SSL("imap.gmail.com")15 mail.login(EMAIL, PASSWORD)16 mail.select("inbox")17 18 status, messages = mail.search(None, "UNSEEN")19 20 if status != "OK":21 return []22 23 for num in messages[0].split():24 status, msg_data = mail.fetch(num, "(RFC822)")25 26 if status != "OK":27 continue28 29 msg = email.message_from_bytes(msg_data[0][1])30 31 subject = msg["subject"]32 33 body = ""34 35 if msg.is_multipart():36 for part in msg.walk():37 if part.get_content_type() == "text/plain":38 body = part.get_payload(decode=True).decode(errors="ignore")39 break40 else:41 body = msg.get_payload(decode=True).decode(errors="ignore")42 43 emails.append({44 "subject": subject,45 "body": body46 })47 48 mail.logout()49 50 except Exception as e:51 print("Email fetch error:", e)52 return []53 54 return emails