"""안내문 메일 일괄 발송(2026-10-27) — 보내는 사람 본인 Gmail(입출고·휴가와 같은 Gmail 연결, gmail.send 만)로 한 사람에 한 통. 라우터가 고른 줄을 '발송중'으로 잡은 뒤(db.claim_for_send — 두 번 눌러도 한 번) 응답하고, 이 함수가 백그라운드에서 차례로 보낸다. 줄마다 {이름} 을 바꾼 제목·본문 + 설정 사진(본문 아래, cid)을 만들어 보내고 보냄/실패와 기록(outreach_logs)을 남긴다. 본문에 {이름} 이 있는데 이름이 빈 줄은 보내지 않고 실패('이름 없음'). Gmail 연결이 끊기면 남은 줄은 실패(다시 연결 안내). """ from __future__ import annotations import logging import time from typing import Any from . import store logger = logging.getLogger("app.outreach.send") SEND_GAP_SECONDS = 1.0 # 한 통마다 쉬는 시간 — Gmail 이 짧은 시간에 몰린 발송을 막지 않게 def _cid(image_id: int) -> str: return f"outreach-{image_id}@dbx" def build_mail(template: dict[str, Any], images: list[dict[str, Any]], *, name: str, sender_name: str, sender_email: str, to: str) -> bytes: from app.modules.inout import gmail # noqa: WPS433 cids = [_cid(int(im["id"])) for im in images] return gmail.build_message( sender_name=template.get("sender_name") or sender_name, sender_email=sender_email, to=[to], cc=[], subject=store.subject_for(template, name), text=store.plain_text(template, name), html=store.html_body(template, name, cids), inline_images=[{"cid": c, "data": bytes(im["data"])} for c, im in zip(cids, images)], ) def send_batch(db: Any, inout_store: Any, *, rows: list[dict[str, Any]], user: dict[str, Any], gap: float = SEND_GAP_SECONDS) -> dict[str, int]: """잡아 둔 줄(rows)을 차례로 보낸다 — {"sent", "failed"}. 예외를 밖으로 던지지 않는다(줄마다 결과를 남김).""" from app.modules.inout import gmail # noqa: WPS433 email = str(user.get("email") or "").lower() result = {"sent": 0, "failed": 0} try: template = db.get_template() images = db.list_images(with_data=True) subject_of = lambda r: store.subject_for(template, r["name"]) # noqa: E731 row = inout_store.gmail_token(email) if inout_store is not None else None refresh = gmail.decrypt_token(email, row["refresh_token_enc"]) if row else None except Exception as exc: # noqa: BLE001 — 준비 실패 = 잡아 둔 줄 모두 실패(발송중으로 남지 않게) for r in rows: db.finish_send(r["id"], ok=False, via="gmail", by=email, subject="", error=f"보낼 준비 실패: {exc}") result["failed"] = len(rows) return result stop_reason = "" if refresh else "Gmail 이 연결되지 않았습니다 — 안내문 발송 → [Gmail 연결] 뒤 다시 보내세요." need_name = store.needs_name(template) for i, r in enumerate(rows): if stop_reason: db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=stop_reason) result["failed"] += 1 continue if need_name and not (r.get("name") or "").strip(): db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error="이름 없음 — 본문에 {이름} 이 있어 이름을 넣은 뒤 다시 보내세요.") result["failed"] += 1 continue try: raw = build_mail(template, images, name=r["name"], sender_name=str(user.get("name") or ""), sender_email=email, to=r["handle"]) gmail.send(refresh, raw) except gmail.GmailNotConnected as exc: try: inout_store.delete_gmail_token(email) except Exception: # noqa: BLE001 pass stop_reason = f"Gmail 연결이 끊겼습니다 — 다시 연결한 뒤 보내세요. ({exc})" db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=stop_reason) result["failed"] += 1 continue except Exception as exc: # noqa: BLE001 — 그 사람만 실패(받는 주소 오류 등), 다음 사람은 계속 db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=str(exc)[:300]) result["failed"] += 1 continue db.finish_send(r["id"], ok=True, via="gmail", by=email, subject=subject_of(r)) result["sent"] += 1 if gap and i < len(rows) - 1: time.sleep(gap) try: if inout_store is not None and result["sent"]: inout_store.mark_gmail(email) except Exception: # noqa: BLE001 pass logger.info("안내문 메일 %s: 보냄 %s · 실패 %s", email, result["sent"], result["failed"]) return result