
import os, imaplib, email, re, html
from email.policy import default
from pathlib import Path
creds={}
for line in Path('/opt/data/secrets/.yahoo-credentials').read_text().splitlines():
    if '=' in line:
        k,v=line.split('=',1); creds[k.strip()]=v.strip().strip('"').strip("'")
m=imaplib.IMAP4_SSL('imap.mail.yahoo.com',993); m.login(creds['YAHOO_EMAIL'],creds['YAHOO_APP_PASSWORD']); m.select('INBOX', readonly=True)
st,data=m.fetch('9976','(BODY.PEEK[])')
raw=next(item[1] for item in data if isinstance(item,tuple) and isinstance(item[1],(bytes,bytearray)))
msg=email.message_from_bytes(raw, policy=default)
print('From:', msg.get('From'))
print('To:', msg.get('To'))
print('Cc:', msg.get('Cc'))
print('Date:', msg.get('Date'))
print('Subject:', msg.get('Subject'))
print('Message-ID:', msg.get('Message-ID'))
print('\n--- BODY ---')
plain=[]; htmls=[]
if msg.is_multipart():
    for part in msg.walk():
        if part.get_content_disposition()=='attachment': continue
        if part.get_content_type()=='text/plain':
            plain.append(part.get_content())
        elif part.get_content_type()=='text/html':
            htmls.append(part.get_content())
else:
    plain.append(msg.get_content())
body='\n'.join(plain).strip()
if not body and htmls:
    txt='\n'.join(htmls)
    txt=re.sub(r'<br\s*/?>','\n',txt,flags=re.I)
    txt=re.sub(r'</p\s*>','\n',txt,flags=re.I)
    txt=re.sub(r'<style.*?</style>|<script.*?</script>',' ',txt,flags=re.I|re.S)
    txt=re.sub(r'<[^>]+>',' ',txt)
    body=html.unescape(txt)
body=re.sub(r'\n{3,}','\n\n',body)
print(body[:15000])
print('\n--- ATTACHMENTS ---')
for part in msg.walk():
    fn=part.get_filename()
    if fn:
        print(fn, part.get_content_type(), len(part.get_payload(decode=True) or b''))
m.logout()
