# -*- coding: utf-8 -*- """MLH promo mailbox watchdog: prints ONLY when a NEW relevant promo email is found. Cron-friendly (every 20 min). State: promo_state.json; dumps: promo_email_.html, promo_found.json. Stdlib only.""" import imaplib, email, re, json, os, time from email.header import decode_header CFG = json.load(open("creds.json")) STATE = "promo_state.json" def hdecode(s): if not s: return "" try: return "".join(p.decode(c or "utf-8", errors="replace") if isinstance(p, bytes) else str(p) for p, c in decode_header(s)) except Exception: return str(s) def main(): st = {"seen": []} if os.path.exists(STATE): try: st = json.load(open(STATE)) except Exception: pass seen = set(st.get("seen", [])) M = imaplib.IMAP4_SSL("imap.gmail.com", timeout=60) M.login(CFG["imap_user"], CFG["imap_pass"]) M.select("INBOX") typ, data = M.search(None, "ALL") ids = data[0].split() new_hits = [] for i in reversed(ids[-40:]): iid = i.decode() if isinstance(i, bytes) else str(i) if iid in seen: continue typ, hd = M.fetch(i, "(BODY.PEEK[HEADER.FIELDS (DATE FROM SUBJECT TO)])") hs = hd[0][1] hs = hs.decode(errors="replace") if isinstance(hs, bytes) else str(hs) seen.add(iid) blob = hs.lower() hit = ("cursor" in blob) or ("promo" in blob) or ("x.ai" in blob) or ("redeem" in blob) frm = any(k in blob for k in ("mlh", "cursor", "x.ai", "spacexai", "grok")) if hit or frm: typ2, md = M.fetch(i, "(BODY.PEEK[])") raw = md[0][1] msg = email.message_from_bytes(raw) frmh = hdecode(msg.get("From", "")).lower() subj = hdecode(msg.get("Subject", "")) body = "" for part in msg.walk(): if part.get_content_type() in ("text/plain", "text/html"): try: pl = part.get_payload(decode=True) body += pl.decode(errors="replace") if isinstance(pl, bytes) else str(pl) except Exception: pass low = (frmh + subj + body).lower() relevant = (("cursor" in low and any(k in low for k in ("promo", "code", "pro ", "redeem"))) or ("redeem" in low and "cursor" in low)) if relevant and "verify your identity" not in subj.lower(): txt = re.sub(r"<[^>]*>", " ", body); txt = re.sub(r"\s+", " ", txt) codes = re.findall(r"\b[A-Z0-9]{4,8}-[A-Z0-9]{4,8}(?:-[A-Z0-9]{4,8})?\b", txt) codes += re.findall(r"(?i)promo[^A-Za-z0-9]{0,15}([A-Za-z0-9_-]{6,32})", txt) links = [l for l in set(re.findall(r"https?://[^\s\"<>'\\]+", body)) if any(k in l.lower() for k in ("cursor", "promo", "redeem", "claim"))] open("promo_email_%s.html" % iid, "w", encoding="utf-8").write(body[:500000]) new_hits.append({"id": iid, "from": frmh[:80], "subject": subj[:120], "codes": codes[:5], "links": links[:5], "snippet": txt[:600]}) M.logout() st["seen"] = list(seen)[-500:] st["last_run"] = time.strftime("%Y-%m-%d %H:%M:%S") json.dump(st, open(STATE, "w")) if new_hits: json.dump(new_hits, open("promo_found.json", "w"), ensure_ascii=False, indent=1) out = ["PROMO EMAIL FOUND (%d):" % len(new_hits)] for h2 in new_hits: out.append("From: %s | Subj: %s" % (h2["from"], h2["subject"])) if h2["codes"]: out.append("CODES: %s" % h2["codes"]) if h2["links"]: out.append("LINKS: %s" % h2["links"][:2]) out.append("SNIPPET: %s" % h2["snippet"][:400]) print("\n".join(out).encode("ascii", "replace").decode()) if __name__ == "__main__": try: main() except Exception as e: print("WATCH ERR: %s" % str(e)[:150])