Files
eden-autoreg/mail_read.py
T
2026-11-01 03:36:34 +03:00

71 lines
2.9 KiB
Python

import sys, imaplib, email, re, time, html
from email.header import decode_header
def rd(h):
if not h: return ''
out = []
for part, enc in decode_header(h):
if isinstance(part, bytes):
out.append(part.decode(enc or 'utf-8', 'replace'))
else:
out.append(part)
return ''.join(out)
def body_text(msg):
txt = ''
if msg.is_multipart():
for p in msg.walk():
if p.get_content_type() == 'text/plain':
try: txt += p.get_payload(decode=True).decode(p.get_content_charset() or 'utf-8', 'replace')
except Exception: pass
elif p.get_content_type() == 'text/html' and not txt:
try: txt += html.unescape(re.sub(r'<[^>]+>', ' ', p.get_payload(decode=True).decode(p.get_content_charset() or 'utf-8', 'replace')))
except Exception: pass
else:
try: txt = msg.get_payload(decode=True).decode(msg.get_content_charset() or 'utf-8', 'replace')
except Exception: txt = str(msg.get_payload())
return txt
def read(user, pw, host, sender_filter='', wait=90, limit=5, code_only=False):
end = time.time() + wait
last = ''
while True:
try:
M = imaplib.IMAP4_SSL(host, 993, timeout=30)
M.login(user, pw)
M.select('INBOX')
typ, data = M.search(None, 'ALL')
ids = data[0].split()[-limit * 3:]
found = []
for i in reversed(ids):
typ, d = M.fetch(i, '(RFC822)')
if not d or not isinstance(d[0], tuple): continue
msg = email.message_from_bytes(d[0][1])
subj = rd(msg.get('Subject'))
frm = rd(msg.get('From'))
if sender_filter and sender_filter.lower() not in (frm + ' ' + subj).lower():
continue
b = body_text(msg)
codes = re.findall(r'\b([0-9]{6}|[0-9A-Za-z]{6})\b', b)
links = re.findall(r'https?://[^\s"<>)]{20,200}', b)
found.append({'date': msg.get('Date'), 'from': frm[:80], 'subj': subj[:100],
'codes': list(dict.fromkeys(codes))[:5],
'links': [l for l in links if 'unsub' not in l.lower()][:6],
'snippet': re.sub(r'\s+', ' ', b)[:400]})
M.logout()
if found:
return {'ok': True, 'msgs': found}
last = 'no-mail'
except Exception as e:
last = 'ERR ' + str(e)[:120]
if time.time() > end:
return {'ok': False, 'err': last}
time.sleep(8)
if __name__ == '__main__':
user, pw = sys.argv[1], sys.argv[2]
flt = sys.argv[3] if len(sys.argv) > 3 else ''
wait = int(sys.argv[4]) if len(sys.argv) > 4 else 90
host = sys.argv[5] if len(sys.argv) > 5 else 'secureimap.t-online.de'
import json
print(json.dumps(read(user, pw, host, flt, wait), ensure_ascii=False)[:3000])