151 lines
4.7 KiB
Python
151 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
||
"""mail_reader.py <email> <password> <min_ts> <timeout> [from_filter]
|
||
|
||
Держит ОДНО IMAP-соединение и опрашивает его, вместо логина на каждом круге:
|
||
Gmail/aliyun/rambler отбивают частые повторные логины, и скрипт возвращает
|
||
NOLINK на письмо, которое реально пришло.
|
||
|
||
Сканирует все папки один раз, дальше только те, где что-то было, + INBOX/Junk.
|
||
|
||
Выход: одна строка с URL verify?token=... либо NOLINK (exit 1).
|
||
"""
|
||
import email
|
||
import html
|
||
import imaplib
|
||
import re
|
||
import sys
|
||
import time
|
||
from email.utils import parsedate_to_datetime
|
||
|
||
EMAIL_ = sys.argv[1]
|
||
PW = sys.argv[2]
|
||
MIN_TS = int(sys.argv[3]) if len(sys.argv) > 3 else 0
|
||
TIMEOUT = int(sys.argv[4]) if len(sys.argv) > 4 else 120
|
||
FROMF = (sys.argv[5] if len(sys.argv) > 5 else "unrestricted").lower()
|
||
|
||
DOM = EMAIL_.split("@")[-1].lower()
|
||
|
||
# известные IMAP-хосты; для остальных пробуем imap.<домен> и mail.<домен>
|
||
KNOWN = {
|
||
"gmail.com": ["imap.gmail.com"],
|
||
"t-online.de": ["secureimap.t-online.de"],
|
||
"singnet.com.sg": ["imap.singnet.com.sg"],
|
||
"gazeta.pl": ["imap.gazeta.pl"],
|
||
"rambler.ru": ["imap.rambler.ru"],
|
||
"aliyun.com": ["imap.aliyun.com"],
|
||
"ldsubmissions.com": ["mail.ldsubmissions.com", "imap.ldsubmissions.com"],
|
||
}
|
||
hosts = KNOWN.get(DOM, ["imap." + DOM, "mail." + DOM])
|
||
|
||
VERIFY = re.compile(r"https?://[^\s\"'<>]*magic-link/verify\?token=([A-Za-z0-9_\-]{16,})([^\s\"'<>]*)")
|
||
|
||
|
||
def body_text(msg):
|
||
"""Текст письма с декодом quoted-printable: без этого токен ссылки обрезается."""
|
||
parts = []
|
||
for p in (msg.walk() if msg.is_multipart() else [msg]):
|
||
try:
|
||
if p.get_content_type() not in ("text/plain", "text/html"):
|
||
continue
|
||
payload = p.get_payload(decode=True)
|
||
if payload:
|
||
parts.append(payload.decode(p.get_content_charset() or "utf-8", "replace"))
|
||
except Exception:
|
||
pass
|
||
t = "\n".join(parts).replace("=\r\n", "").replace("=\n", "")
|
||
return html.unescape(t)
|
||
|
||
|
||
def msg_ts(msg):
|
||
try:
|
||
return int(parsedate_to_datetime(msg.get("Date")).timestamp())
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
def folders(m):
|
||
out = []
|
||
try:
|
||
typ, boxes = m.list()
|
||
for b in boxes or []:
|
||
s = b.decode("utf-8", "replace") if isinstance(b, bytes) else str(b)
|
||
mm = re.search(r'"([^"]*)"\s*$', s)
|
||
out.append(mm.group(1) if mm else s.split()[-1].strip('"'))
|
||
except Exception:
|
||
pass
|
||
for extra in ("INBOX", "Junk", "Spam", "Bulk"):
|
||
if extra not in out:
|
||
out.append(extra)
|
||
return out
|
||
|
||
|
||
def scan(m, boxes):
|
||
for box in boxes:
|
||
try:
|
||
m.select(box, readonly=True)
|
||
except Exception:
|
||
continue
|
||
try:
|
||
typ, d = m.search(None, "ALL")
|
||
ids = d[0].split()[-30:] if d and d[0] else []
|
||
except Exception:
|
||
continue
|
||
for i in reversed(ids):
|
||
try:
|
||
t, msg = m.fetch(i, "(BODY.PEEK[])")
|
||
raw = msg[0][1]
|
||
except Exception:
|
||
continue
|
||
em = email.message_from_bytes(raw)
|
||
frm = (em.get("From") or "").lower()
|
||
if FROMF not in frm and FROMF not in raw.decode("utf-8", "replace").lower()[:4000]:
|
||
continue
|
||
ts = msg_ts(em)
|
||
if MIN_TS and ts and ts < MIN_TS - 3600:
|
||
continue
|
||
mm = VERIFY.search(body_text(em))
|
||
if mm:
|
||
return "https://unrestricted.sh/api/auth/magic-link/verify?token=%s%s" % (
|
||
mm.group(1), html.unescape(mm.group(2)))
|
||
return None
|
||
|
||
|
||
def main():
|
||
t0 = time.time()
|
||
m = None
|
||
boxes = None
|
||
while time.time() - t0 < TIMEOUT:
|
||
if m is None:
|
||
for host in hosts:
|
||
try:
|
||
m = imaplib.IMAP4_SSL(host, 993)
|
||
m.login(EMAIL_, PW)
|
||
boxes = folders(m)
|
||
break
|
||
except Exception:
|
||
m = None
|
||
if m is None:
|
||
time.sleep(15)
|
||
continue
|
||
try:
|
||
link = scan(m, boxes)
|
||
if link:
|
||
print(link)
|
||
sys.exit(0)
|
||
except Exception:
|
||
try:
|
||
m.logout()
|
||
except Exception:
|
||
pass
|
||
m = None
|
||
time.sleep(10)
|
||
try:
|
||
m.logout()
|
||
except Exception:
|
||
pass
|
||
print("NOLINK")
|
||
sys.exit(1)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |