mime = message_builder.build_mime_message( from_email=account.email, # real authenticated account; never spoofed to_email=cr.email, subject=subject, html_body=result_html if campaign.message_type != "plain" else "", text_body=result_text, attachments=attachments, unsubscribe_url=unsub_url if campaign.unsubscribe_enabled else "", unsubscribe_mailto=f"{account.email}?subject=unsubscribe", ) # ------------------------------------------------------------- send for real token = (db.execute(select(OAuthToken) .where(OAuthToken.account_id == account.id))).scalar_one_or_none() if token is None: cr.status = "perm_failed" cr.last_error = "No OAuth token for account" campaign.failed_count += 1 db.commit() return {"ok": False, "status": "perm_failed", "reason": "missing token"} cr.status = "processing" cr.attempt_count += 1 if job: job.status = "processing" job.attempts = cr.attempt_count attempt = SendAttempt( send_job_id=job.id if job else 0, campaign_id=campaign.id, gmail_account_id=account.id, recipient_email=cr.email, subject=subject, template_name=template.name, attachment_names=att_names, method=account.sending_method, outcome="submitted", retry_no=cr.attempt_count - 1, ) db.add(attempt) db.commit() try: client = build_gmail_client_from_account(account, token) except Exception as e: return _handle_send_error(db, self, campaign, cr, job, account, attempt, str(e)) try: if client.method == "smtp": out = client.send_mime_smtp(mime) else: out = client.send_mime_api(mime) except googleapiclient.errors.HttpError as e: content = e.content.decode(errors="replace") if isinstance(e.content, bytes) else str(e.content) return _handle_send_error(db, self, campaign, cr, job, account, attempt, f"Gmail API error {e.resp.status}: {content[:300]}")