Repository navigation
Expand file tree
/
Copy pathreplier.py
More file actions
283 lines (236 loc) · 9.42 KB
/
Copy pathreplier.py
File metadata and controls
283 lines (236 loc) · 9.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""IMAP polling + auto-reply.
Architecture:
Each domain has a single catch-all mailbox (e.g. warmup@example-a.com) that
receives all mail addressed to any inbox on that domain. We log in once per
domain per poll cycle, walk new messages, and for each one:
1. Match the incoming Message-ID against send_log — only OUR own warmup
traffic is eligible for a reply (random outsider mail is ignored).
2. Parse the `To:` header to identify which fleet inbox the mail was
addressed to — that's the identity we reply from.
3. Schedule a delayed reply 30min–4h out on a daemon thread.
Replies are sent through the configured SMTP provider with proper In-Reply-To / References
headers so the thread stays intact in the receiving client.
"""
from __future__ import annotations
import email
import imaplib
import logging
import random
import sqlite3
import threading
import time
from datetime import date, timedelta
from email.message import EmailMessage
from email.utils import getaddresses, make_msgid, parseaddr
from typing import Optional
import database
from sender import SmtpTransport
log = logging.getLogger(__name__)
STATUS_DUPLICATE = "duplicate"
STATUS_NOT_OURS = "not-ours"
STATUS_NO_TARGET = "no-target"
STATUS_SELF = "self"
STATUS_ALREADY_REPLIED = "already-replied"
STATUS_SCHEDULED = "scheduled"
def handle_inbound_message(
msg: email.message.Message,
dedup_source: str,
dedup_uid: str,
fleet_by_email: dict[str, sqlite3.Row],
smtp: SmtpTransport,
reply_delay_minutes: tuple[int, int],
content_module,
) -> str:
"""Decide and (maybe) schedule a reply for one already-parsed inbound message.
This is the exact decision sequence formerly inlined in poll_domain, lifted
so the IMAP path and the Resend path share identical logic. Every terminal
branch marks the message processed (dedup), matching prior behavior.
The outer pre-FETCH is_processed check in poll_domain is a network-efficiency optimization; the re-check here also covers callers (e.g. the queue drain) that have no pre-filter.
"""
if database.is_processed(dedup_source, dedup_uid):
return STATUS_DUPLICATE
mid = _extract_message_id(msg)
original_send = database.find_send_by_message_id(mid) if mid else None
if not original_send:
database.mark_processed(dedup_source, dedup_uid, mid)
return STATUS_NOT_OURS
target = _resolve_target_inbox(msg, fleet_by_email)
if not target:
database.mark_processed(dedup_source, dedup_uid, mid)
return STATUS_NO_TARGET
sender_addr = parseaddr(msg.get("From", ""))[1].lower()
if not sender_addr or sender_addr == target["email"].lower():
database.mark_processed(dedup_source, dedup_uid, mid)
return STATUS_SELF
if database.already_replied(mid or ""):
database.mark_processed(dedup_source, dedup_uid, mid)
return STATUS_ALREADY_REPLIED
sender_first = sender_addr.split("@", 1)[0].split(".")[0].capitalize()
subject = msg.get("Subject", "(no subject)")
_schedule_delayed_reply(
smtp, target, sender_addr, sender_first,
subject, mid or "",
reply_delay_minutes, content_module,
)
database.mark_processed(dedup_source, dedup_uid, mid)
return STATUS_SCHEDULED
class ImapHost:
"""Per-domain IMAP server info."""
__slots__ = ("host", "port")
def __init__(self, host: str, port: int) -> None:
self.host = host
self.port = port
class CatchallCredential:
__slots__ = ("imap_user", "imap_password")
def __init__(self, imap_user: str, imap_password: str) -> None:
self.imap_user = imap_user
self.imap_password = imap_password
def _connect_imap(host: ImapHost, user: str, password: str) -> imaplib.IMAP4_SSL:
conn = imaplib.IMAP4_SSL(host.host, host.port)
conn.login(user, password)
return conn
def _extract_message_id(msg: email.message.Message) -> Optional[str]:
mid = msg.get("Message-ID")
return mid.strip() if mid else None
def _all_to_addresses(msg: email.message.Message) -> list[str]:
"""Return every address that appeared in To: or Cc: headers, lowercased."""
raws = msg.get_all("To", []) + msg.get_all("Cc", [])
return [addr.lower() for _, addr in getaddresses(raws) if addr]
def _resolve_target_inbox(
msg: email.message.Message, fleet_by_email: dict[str, sqlite3.Row]
) -> Optional[sqlite3.Row]:
"""Which of our fleet inboxes was this message addressed to?"""
for addr in _all_to_addresses(msg):
row = fleet_by_email.get(addr)
if row:
return row
return None
def _build_reply(
from_inbox_row: sqlite3.Row,
to_email: str,
to_first: str,
original_subject: str,
original_message_id: str,
content_module,
) -> EmailMessage:
subject, body, _ = content_module.generate_reply(
from_inbox_row["email"], from_inbox_row["first_name"], original_subject
)
reply = EmailMessage()
reply["From"] = f"{from_inbox_row['first_name']} <{from_inbox_row['email']}>"
reply["To"] = f"{to_first} <{to_email}>"
reply["Subject"] = subject
reply["In-Reply-To"] = original_message_id
reply["References"] = original_message_id
sender_domain = from_inbox_row["email"].split("@", 1)[1]
reply["Message-ID"] = make_msgid(domain=sender_domain)
reply.set_content(body)
return reply
def _schedule_delayed_reply(
smtp: SmtpTransport,
from_inbox: sqlite3.Row,
to_email: str,
to_first: str,
original_subject: str,
original_message_id: str,
delay_minutes_range: tuple[int, int],
content_module,
) -> None:
"""Spawn a daemon thread that sleeps a random delay, then sends the reply.
At steady state (~875 replies/day), an in-process thread-per-reply costs ~875
sleeping threads — well under any OS limit and far simpler than re-entering
APScheduler with a per-message DateTrigger."""
delay_minutes = random.randint(*delay_minutes_range)
delay_seconds = delay_minutes * 60
def _later() -> None:
time.sleep(delay_seconds)
if database.already_replied(original_message_id):
return
reply = _build_reply(
from_inbox, to_email, to_first, original_subject, original_message_id, content_module
)
try:
smtp.send(reply)
database.log_reply(
original_message_id, reply["Message-ID"],
from_inbox["email"], to_email,
)
log.info(
"[REPLY] %s -> %s | %s | delay: %dmin",
from_inbox["email"], to_email, reply["Subject"], delay_minutes,
)
except Exception as exc: # noqa: BLE001
log.error("[REPLY-FAIL] %s -> %s: %s", from_inbox["email"], to_email, exc)
threading.Thread(target=_later, daemon=True).start()
def schedule_recovery_reply(
smtp: SmtpTransport,
send_row: sqlite3.Row,
reply_delay_minutes: tuple[int, int],
content_module,
) -> bool:
"""Re-arm a reply that was scheduled in a previous process run but lost when
the process died. Looks up the recipient identity in the inboxes table and
spawns the standard delayed-reply thread.
Returns True if a reply was scheduled, False if we couldn't (e.g. recipient
inbox no longer in DB)."""
target = database.inbox_by_email(send_row["to_email"])
if not target:
return False
_schedule_delayed_reply(
smtp,
target,
send_row["from_email"],
send_row["from_email"].split("@", 1)[0].split(".")[0].capitalize(),
send_row["subject"],
send_row["message_id"],
reply_delay_minutes,
content_module,
)
return True
def poll_domain(
domain: str,
host: ImapHost,
creds: CatchallCredential,
smtp: SmtpTransport,
reply_delay_minutes: tuple[int, int],
content_module,
) -> None:
"""Poll the catch-all mailbox for one domain. Schedule replies for any new
warmup messages addressed to fleet inboxes on this domain."""
fleet_inboxes = database.inboxes_for_domain(domain)
if not fleet_inboxes:
return
fleet_by_email = {inbox["email"].lower(): inbox for inbox in fleet_inboxes}
try:
conn = _connect_imap(host, creds.imap_user, creds.imap_password)
except Exception as exc: # noqa: BLE001
log.error("[IMAP-CONNECT-FAIL] %s: %s", creds.imap_user, exc)
return
try:
conn.select("INBOX")
# IMAP SEARCH SINCE expects DD-Mon-YYYY (RFC 3501). "1-DAY" is invalid.
since_date = (date.today() - timedelta(days=1)).strftime("%d-%b-%Y")
typ, data = conn.uid("SEARCH", None, "SINCE", since_date)
if typ != "OK" or not data or not data[0]:
return
for uid in data[0].split():
uid_str = uid.decode()
if database.is_processed(creds.imap_user, uid_str):
continue
typ, fetched = conn.uid("FETCH", uid, "(RFC822)")
if typ != "OK" or not fetched:
continue
raw = fetched[0][1] if isinstance(fetched[0], tuple) else None
if not raw:
continue
msg = email.message_from_bytes(raw)
status = handle_inbound_message(
msg, creds.imap_user, uid_str, fleet_by_email,
smtp, reply_delay_minutes, content_module,
)
log.debug("[IMAP-MSG] uid=%s status=%s", uid_str, status)
finally:
try:
conn.logout()
except Exception: # noqa: BLE001
pass