284 lines
9.4 KiB
Python
284 lines
9.4 KiB
Python
"""Mailbox pool with multi-provider IMAP support.
|
|
|
|
Handles many pool files, detects the IMAP host by domain, falls back across
|
|
candidate hosts, supports POP3 providers (rediffmail) and STARTTLS.
|
|
|
|
Pool line format: email:password
|
|
"""
|
|
import email as email_lib
|
|
import imaplib
|
|
import os
|
|
import poplib
|
|
import random
|
|
import re
|
|
import socket
|
|
import ssl
|
|
import time
|
|
|
|
# domain -> IMAP host (993, SSL)
|
|
IMAP_PRESETS = {
|
|
't-online.de': 'secureimap.t-online.de',
|
|
'gmail.com': 'imap.gmail.com',
|
|
'googlemail.com': 'imap.gmail.com',
|
|
'outlook.com': 'outlook.office365.com',
|
|
'hotmail.com': 'outlook.office365.com',
|
|
'live.com': 'outlook.office365.com',
|
|
'yahoo.com': 'imap.mail.yahoo.com',
|
|
'rambler.ru': 'imap.rambler.ru',
|
|
'lenta.ru': 'imap.rambler.ru',
|
|
'ro.ru': 'imap.rambler.ru',
|
|
'mail.ru': 'imap.mail.ru',
|
|
'inbox.ru': 'imap.mail.ru',
|
|
'bk.ru': 'imap.mail.ru',
|
|
'list.ru': 'imap.mail.ru',
|
|
'yandex.ru': 'imap.yandex.ru',
|
|
'ya.ru': 'imap.yandex.ru',
|
|
'i.ua': 'imap.i.ua',
|
|
'ukr.net': 'imap.ukr.net',
|
|
'aliyun.com': 'imap.aliyun.com',
|
|
'gmx.de': 'imap.gmx.net',
|
|
'gmx.net': 'imap.gmx.net',
|
|
'web.de': 'imap.web.de',
|
|
'singnet.com.sg': 'imap.singnet.com.sg',
|
|
'icn.od.ua': 'imap.icn.od.ua',
|
|
'protonmail.com': '127.0.0.1', # bridge only
|
|
'zoho.com': 'imap.zoho.com',
|
|
'aol.com': 'imap.aol.com',
|
|
'mail.com': 'imap.mail.com',
|
|
'email.com': 'imap.mail.com',
|
|
'posteo.de': 'posteo.de',
|
|
'gmx.at': 'imap.gmx.net',
|
|
'seznam.cz': 'imap.seznam.cz',
|
|
'interia.pl': 'imap.interia.pl',
|
|
'o2.pl': 'imap.o2.pl',
|
|
'wp.pl': 'imap.wp.pl',
|
|
'onet.pl': 'imap.onet.pl',
|
|
'naver.com': 'imap.naver.com',
|
|
'daum.net': 'imap.daum.net',
|
|
}
|
|
|
|
# domain -> POP3 host (995, SSL) for providers without IMAP
|
|
POP3_PRESETS = {
|
|
'rediffmail.com': 'pop.rediffmail.com',
|
|
}
|
|
|
|
|
|
def domain_of(addr: str) -> str:
|
|
return addr.rsplit('@', 1)[-1].lower()
|
|
|
|
|
|
def imap_candidates(addr: str):
|
|
d = domain_of(addr)
|
|
hosts = []
|
|
if d in IMAP_PRESETS:
|
|
hosts.append(IMAP_PRESETS[d])
|
|
hosts += [f'imap.{d}', f'mail.{d}', f'imap.mail.{d}', d]
|
|
seen, out = set(), []
|
|
for h in hosts:
|
|
if h and h not in seen:
|
|
seen.add(h)
|
|
out.append(h)
|
|
return out
|
|
|
|
|
|
class Mailbox:
|
|
"""One mailbox: knows how to fetch messages from it."""
|
|
|
|
def __init__(self, addr: str, password: str, timeout: int = 20):
|
|
self.addr = addr
|
|
self.password = password
|
|
self.timeout = timeout
|
|
self.last_error = ''
|
|
|
|
# ---------- IMAP ----------
|
|
def _imap_connect(self):
|
|
d = domain_of(self.addr)
|
|
last = ''
|
|
for host in imap_candidates(self.addr):
|
|
try:
|
|
socket.create_connection((host, 993), timeout=6).close()
|
|
except Exception as e:
|
|
last = f'{host}: {type(e).__name__}'
|
|
continue
|
|
try:
|
|
m = imaplib.IMAP4_SSL(host, timeout=self.timeout)
|
|
m.login(self.addr, self.password)
|
|
return m, host
|
|
except Exception as e:
|
|
last = f'{host}: {type(e).__name__}: {str(e)[:50]}'
|
|
continue
|
|
self.last_error = last or 'no imap host reachable'
|
|
return None, None
|
|
|
|
def _imap_search_from(self, m, sender: str, since_uid: int = 0, limit: int = 8):
|
|
"""Some servers (aliyun, rambler) reject SEARCH FROM; fall back to ALL + python filter."""
|
|
m.select('INBOX')
|
|
ids = []
|
|
try:
|
|
typ, data = m.search(None, f'(FROM "{sender}")')
|
|
if typ == 'OK' and data and data[0]:
|
|
ids = data[0].split()
|
|
except Exception:
|
|
ids = []
|
|
if not ids:
|
|
try:
|
|
typ, data = m.search(None, 'ALL')
|
|
if typ == 'OK' and data and data[0]:
|
|
ids = data[0].split()[-60:]
|
|
ids = [i for i in ids if self._from_matches(m, i, sender)]
|
|
except Exception:
|
|
ids = []
|
|
if since_uid:
|
|
ids = [i for i in ids if int(i) > since_uid]
|
|
return ids[-limit:]
|
|
|
|
def _from_matches(self, m, uid: bytes, sender: str) -> bool:
|
|
try:
|
|
typ, md = m.fetch(uid, '(BODY.PEEK[HEADER.FIELDS (FROM)])')
|
|
if not md or not md[0]:
|
|
return False
|
|
raw = md[0][1]
|
|
if isinstance(raw, tuple):
|
|
raw = raw[0]
|
|
return sender.lower() in raw.decode('utf-8', 'ignore').lower()
|
|
except Exception:
|
|
return False
|
|
|
|
def _read_msg(self, m, uid: bytes) -> str:
|
|
typ, md = m.fetch(uid, '(RFC822)')
|
|
if not md or not md[0]:
|
|
return ''
|
|
msg = email_lib.message_from_bytes(md[0][1])
|
|
body = ''
|
|
if msg.is_multipart():
|
|
for part in msg.walk():
|
|
if part.get_content_type() in ('text/plain', 'text/html'):
|
|
try:
|
|
body += part.get_payload(decode=True).decode('utf-8', 'ignore')
|
|
except Exception:
|
|
pass
|
|
else:
|
|
try:
|
|
body = msg.get_payload(decode=True).decode('utf-8', 'ignore')
|
|
except Exception:
|
|
pass
|
|
return body
|
|
|
|
def wait_for_link(self, sender: str, pattern: str, timeout: int = 180,
|
|
since_uid: int = 0, poll: int = 10):
|
|
"""Poll mailbox for a message from `sender` and return first regex match."""
|
|
rx = re.compile(pattern)
|
|
deadline = time.time() + timeout
|
|
while time.time() < deadline:
|
|
m, host = self._imap_connect()
|
|
if m:
|
|
try:
|
|
for uid in reversed(self._imap_search_from(m, sender, since_uid)):
|
|
body = self._read_msg(m, uid)
|
|
hit = rx.search(body)
|
|
if hit:
|
|
m.logout()
|
|
return hit
|
|
except Exception as e:
|
|
self.last_error = f'{type(e).__name__}: {str(e)[:60]}'
|
|
finally:
|
|
try:
|
|
m.logout()
|
|
except Exception:
|
|
pass
|
|
elif domain_of(self.addr) in POP3_PRESETS:
|
|
hit = self._pop3_lookup(sender, rx)
|
|
if hit:
|
|
return hit
|
|
time.sleep(poll)
|
|
return None
|
|
|
|
# ---------- POP3 ----------
|
|
def _pop3_lookup(self, sender: str, rx):
|
|
host = POP3_PRESETS[domain_of(self.addr)]
|
|
try:
|
|
ctx = ssl.create_default_context()
|
|
try:
|
|
ctx.set_ciphers('DEFAULT@SECLEVEL=1')
|
|
except Exception:
|
|
pass
|
|
p = poplib.POP3_SSL(host, 995, timeout=self.timeout, context=ctx)
|
|
p.user(self.addr)
|
|
p.pass_(self.password)
|
|
count = len(p.list()[1])
|
|
for i in range(count, max(0, count - 15), -1):
|
|
raw = b'\r\n'.join(p.retr(i)[1])
|
|
body = raw.decode('utf-8', 'ignore')
|
|
if sender.lower() not in body.lower():
|
|
continue
|
|
hit = rx.search(body)
|
|
if hit:
|
|
p.quit()
|
|
return hit
|
|
p.quit()
|
|
except Exception as e:
|
|
self.last_error = f'pop3 {type(e).__name__}: {str(e)[:50]}'
|
|
return None
|
|
|
|
def alive(self) -> bool:
|
|
m, host = self._imap_connect()
|
|
if m:
|
|
try:
|
|
m.select('INBOX')
|
|
m.logout()
|
|
return True
|
|
except Exception:
|
|
pass
|
|
d = domain_of(self.addr)
|
|
if d in POP3_PRESETS:
|
|
try:
|
|
p = poplib.POP3_SSL(POP3_PRESETS[d], 995, timeout=self.timeout)
|
|
p.user(self.addr)
|
|
p.pass_(self.password)
|
|
p.quit()
|
|
return True
|
|
except Exception as e:
|
|
self.last_error = f'pop3 {type(e).__name__}'
|
|
return False
|
|
|
|
|
|
class MailboxPool:
|
|
"""Union of several pool files, deduped, with skip-list support."""
|
|
|
|
def __init__(self, files, skip=None):
|
|
self.files = [f for f in files if f and os.path.exists(f)]
|
|
self.skip = {s.lower() for s in (skip or [])}
|
|
self.items = []
|
|
self._load()
|
|
|
|
def _load(self):
|
|
seen = set(self.skip)
|
|
for path in self.files:
|
|
try:
|
|
with open(path, encoding='utf-8', errors='ignore') as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if not line or line.startswith('#') or ':' not in line:
|
|
continue
|
|
addr, pwd = line.split(':', 1)
|
|
addr, pwd = addr.strip(), pwd.strip()
|
|
if '@' not in addr or not pwd:
|
|
continue
|
|
low = addr.lower()
|
|
if low in seen:
|
|
continue
|
|
seen.add(low)
|
|
self.items.append(Mailbox(addr, pwd))
|
|
except Exception:
|
|
continue
|
|
random.shuffle(self.items)
|
|
|
|
def take(self, n: int):
|
|
return self.items[:n]
|
|
|
|
def domains(self):
|
|
from collections import Counter
|
|
return Counter(domain_of(m.addr) for m in self.items).most_common(20)
|
|
|
|
def __len__(self):
|
|
return len(self.items) |