Email delivery
Send
from common_reports import EmailClient
client = EmailClient.from_env("EMAIL")result = client.send( to=["partner1@example.com", "partner2@example.com"], subject="Daily report", html=email.html, # from a rendered document, or any HTML string attachments=email.attachments, # inline images; add files as Attachment or paths)if not result.success: log.error( "email_failed", provider=result.provider, error_type=result.error_type, error=result.error )send() never raises. It returns a SendResult; the fields you read are success, error,
error_type, provider, recipients and message_id. Check success every time.
asend() is the same call for async code.
| Argument | Meaning |
|---|---|
to, cc, bcc | a string or a list of addresses |
html, text | HTML body; text adds a plain-text alternative |
attachments | a list of Attachment objects, paths or (name, bytes) pairs (a render’s .attachments included); True attaches every *.html in the working directory |
reply_to, headers | per-message overrides |
message_id | pin an RFC Message-ID (idempotency key) |
disclose_recipients | True writes visible To/Cc; the default keeps recipients private |
Choose the backend with environment variables
from_env(prefix) reads {prefix}_BACKEND, which can be smtp, gmail or graph.
When it is unset or auto, the client auto-detects the backend: Graph first, then Gmail,
then SMTP. Switching providers is a values change, never a code change.
Gmail API (Google Workspace service account)
| Variable | Required | Notes |
|---|---|---|
EMAIL_GMAIL_USER | yes | the Workspace mailbox the service account acts as |
EMAIL_GMAIL_SERVICE_ACCOUNT_JSON (or _FILE) | yes | the whole key file; its presence selects the API path |
EMAIL_GMAIL_DELEGATED_USER | no | defaults to EMAIL_GMAIL_USER |
EMAIL_GMAIL_SCOPES | no | defaults to https://www.googleapis.com/auth/gmail.modify (send, read, drafts, labels) |
EMAIL_GMAIL_TIMEOUT, EMAIL_GMAIL_MAX_RETRIES | no | 30 s; the retry setting applies to reads only, and sends never retry |
Requires the gmail extra.
Workspace setup (done once for nullcapital.net):
- The From address is the licensed user or a Send mail as alias of it. Reports go
out as
DoNotReply@nullcapital.net, an alias of the delegated mailbox. - The service account’s client ID is authorized under Admin console → Security → API controls → Domain-wide delegation for exactly the scopes the client requests.
- The domain’s SPF includes
_spf.google.com, and Google DKIM (google._domainkey) is published and started. - The key was created in a project where the organization policy
iam.managed.disableServiceAccountKeyCreationis overridden to off.
Doppler (global/prd): EMAIL_GMAIL_USER and EMAIL_GMAIL_SERVICE_ACCOUNT_JSON.
The From address comes from EMAIL_SMTP_SENDER (or EMAIL_FROM).
SMTP
| Variable | Required | Default |
|---|---|---|
EMAIL_SMTP_HOST, EMAIL_SMTP_USER, EMAIL_SMTP_PASSWORD | yes | — |
EMAIL_SMTP_PORT | no | 587 (STARTTLS); 465 uses implicit TLS |
EMAIL_SMTP_USE_SSL, EMAIL_SMTP_USE_TLS, EMAIL_SMTP_TIMEOUT | no | auto, true, 30 s |
Without a service account, EMAIL_GMAIL_USER + EMAIL_GMAIL_PASSWORD (an app password)
sends through Gmail SMTP.
Microsoft Graph
EMAIL_GRAPH_TENANT_ID, EMAIL_GRAPH_CLIENT_ID, EMAIL_GRAPH_CLIENT_SECRET and
EMAIL_GRAPH_SENDER (app-only, Mail.Send). The optional settings are
EMAIL_GRAPH_TIMEOUT and EMAIL_GRAPH_MAX_RETRIES. Graph is send-only here.
Attachments over about 3 MB fail closed, because upload sessions are not implemented.
Account defaults (any backend)
EMAIL_FROM(orEMAIL_SMTP_SENDER): the From address.EMAIL_FROM_NAME: the From display name.EMAIL_REPLY_TO: the default Reply-To address.EMAIL_ATTACHMENT_NOTE: the note shown when files are attached.noneturns it off.
A missing required variable fails construction with one error that names every missing key.
Delivery contract
- Recipients are private by default. No To or Cc header is written. SMTP delivers by
envelope, the Gmail API by a Bcc header it strips, and Graph by
bccRecipients.disclose_recipients=Truewrites visible To and Cc. Replies always disclose their correspondents. - No duplicate deliveries. A send is never retried after an ambiguous failure. Graph
retries only 429, 503 and 504, honoring
Retry-After. - Message structure.
text=produces amultipart/alternativebody. File attachments keep their declared MIME type. Inline images usecid:insidemultipart/related. - The attachment note.
- A classic body gets the plain AlgoReports trailer after file attachments.
- A modern email carries its own styled “Interactive report attached” box instead. The box appears only when files are attached.
- Reads fail loudly.
read()returnsReadBatch(success=False, error=...), never an empty list that looks like “no mail”.
Moving a container to Gmail
This is the order that worked for market-gateways:
- Depend on
common-reports[gmail]>=0.1.9and refresh the lock. Deploy that image first. - Make sure every send checks
result.success. Older alert helpers treated “no exception” as sent. - Add
EMAIL_BACKEND: "gmail"to that deployment. Also addEMAIL_GMAIL_USERandEMAIL_GMAIL_SERVICE_ACCOUNT_JSONto its secret if it does not already pull all ofglobal/prd. - After the rollout, send one real message from the running pod.
- Confirm the message arrived in the inbox. A “sent” log line is not proof.
Mailbox operations
With the Gmail API (and a subset over IMAP), the client can:
search,get_message,get_threadandget_attachment;list_message_refsandlist_thread_refs: one page of the messages or threads a search matches, by identity, with nothing fetched (Gmail API only);reply,draft_reply,create_draft,send_draftanddelete_draft;- work with labels:
list_labels,create_label,delete_labelandmodify_labels; mark_readandmark_unread;get_profile,list_history,watchandstop_watch.
Each operation is gated by client.capability_report(). An unsupported operation returns
a failed result that names the capability. IMAP reads use stable UIDs and BODY.PEEK[],
so monitoring never marks mail as read.
A failed mailbox result, and a failed send, carry status: the HTTP status the provider
refused with, when it gave one (404 not found, 429 too many requests, 5xx the provider
failing). It is a status, not a diagnosis: Gmail answers both a rate limit and a domain
policy with 403, and a service account’s failed sign-in carries no status at all.
A reply goes to the original’s Reply-To, else its sender. A follow-up on a message this
mailbox sent goes to whom that message was sent, as every mail client does. Reply-all adds
the original’s To and Cc. This mailbox is dropped from the recipients (a note it sent
itself stays one), and nobody is addressed twice.
draft_reply saves exactly that reply as a draft in the original’s thread; nothing is
sent until send_draft.
A message’s body is its text and HTML parts that carry no filename and no attachment
disposition, decoded in the charset each part declares; a named .txt is an attachment,
never the body. A body Gmail stores outside the message is fetched by get_message and
get_thread. A history cursor Gmail no longer keeps returns a failed HistoryResult
with expired=True: nothing was read, and only a full resynchronization recovers.
The Gmail API runs each thread’s calls on that thread’s own transport, so the async
methods may run concurrently. client.close() (or with / async with the client)
releases them once the calls in flight have finished.