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]}") except Exception as e: return _handle_send_error(db, self, campaign, cr, job, account, attempt, str(e)) if not out.get("ok"): return _handle_send_error(db, self, campaign, cr, job, account, attempt, out.get("error", "unknown error")) # ------------------------------------------------------------- accepted msg_id = out.get("message_id", "") attempt.outcome = "accepted" attempt.message_id = msg_id attempt.thread_id = out.get("thread_id", "") attempt.provider_response = _sanitize_response(out.get("raw_response"))