Skip to content

common_reports.schemas.emails.configs

Transport configuration schemas — pydantic models with secret-safe creds.

Three config kinds, one from_env(prefix) pattern each:

SmtpConfig outbound send (smtplib). ``{PREFIX}_SMTP_{HOST,PORT,USER,PASSWORD,USE_TLS}``
ImapConfig inbound read (imaplib). ``{PREFIX}_IMAP_{HOST,PORT,USER,PASSWORD,USE_SSL}``
GmailConfig Gmail app-password SMTP ``{PREFIX}_GMAIL_{USER,PASSWORD,...}``
OR the Gmail API (DWD)

PROVIDER-NEUTRAL BY DESIGN. This is a generic package — it does not bake in any specific external mail server. SmtpConfig is one shape for ANY SMTP server (titan, Gmail-SMTP, SES, …): the host is supplied by the consumer (env/config), only the standard submission PORTS (587/993) have generic defaults. The single provider-specific knowledge the package carries is the Gmail backend’s own endpoints (smtp.gmail.com / imap.gmail.com), which is legitimate because Gmail is a first-class supported backend.

Switching providers is therefore a values change, never a code change: titan -> {PREFIX}_SMTP_HOST=smtp.titan.email (+ user/password) gmail -> {PREFIX}_SMTP_HOST=smtp.gmail.com (+ app-password) [backend=“smtp”] gmail -> {PREFIX}_GMAIL_* service account + delegated user [backend=“gmail”, DWD]

Passwords are :class:pydantic.SecretStr — never in logs/repr/model_dump() — and are read from the injected environment only; this module never fetches a secret store and never hardcodes a credential.

pydantic-settings is NOT a dependency (core install stays light), so these are plain BaseModel s with explicit from_env smart constructors.

Classes

GmailConfig

Bases: BaseModel

Gmail transport configuration — two interchangeable paths.

  1. App-password SMTP (simple): smtp.gmail.com:587 STARTTLS with a 16-char app password. Reads {PREFIX}_GMAIL_{USER,PASSWORD}.
  2. Gmail API (optional, [gmail] extra): a service-account JSON with domain-wide delegation, impersonating delegated_user. Reads {PREFIX}_GMAIL_SERVICE_ACCOUNT_FILE (path) or {PREFIX}_GMAIL_SERVICE_ACCOUNT_JSON (inline) + {PREFIX}_GMAIL_DELEGATED_USER.

use_api selects the path; the provider falls back to SMTP when False. from_env infers it when {PREFIX}_GMAIL_USE_API is unset: a service-account JSON means the API path. delegated_user defaults to user (the Workspace mailbox the service account acts as). Least privilege for send-only use: {PREFIX}_GMAIL_SCOPES= https://www.googleapis.com/auth/gmail.send — requested scopes must be authorized for the service account’s client ID in the Admin console. The Gmail endpoint is fixed here because Gmail is the supported backend.

Fields and properties declared here; inherited members belong to the bases above.

delegated_user

delegated_user: Optional[str] = Field(default=None, description='Workspace user to impersonate (domain-wide delegation)')

max_retries

max_retries: int = Field(default=3, ge=0, le=10, description='Gmail API read retries (sends never retry)')

password

password: Optional[SecretStr] = Field(default=None, description='Gmail app password (SMTP path; secret)')

scopes

scopes: tuple[str, ...] = Field(default=(GMAIL_MODIFY_SCOPE,), description='OAuth scopes for the Gmail API path')

service_account_file

service_account_file: Optional[str] = Field(default=None, description='Path to a service-account JSON (API path)')

service_account_json

service_account_json: Optional[SecretStr] = Field(default=None, description='Inline service-account JSON (API path; secret)')

smtp_host

smtp_host: str = Field(default=GMAIL_SMTP_HOST, description='Gmail SMTP host')

smtp_port

smtp_port: int = Field(default=GMAIL_SMTP_PORT, description='Gmail SMTP port')

timeout

timeout: float = Field(default=30.0, gt=0, description='Gmail API socket timeout (seconds)')

use_api

use_api: bool = Field(default=False, description='Use the Gmail API instead of SMTP')

use_tls

use_tls: bool = Field(default=True, description='STARTTLS for the SMTP path')

user

user: str = Field(description='Gmail address / From address')

user_id

user_id: str = Field(default='me', description='Gmail API mailbox userId')

from_env

@classmethod
def from_env(prefix: str = 'EMAIL') -> GmailConfig

Build from {PREFIX}_GMAIL_* env vars.

Reads {PREFIX}_GMAIL_{USER,PASSWORD,USE_TLS,USE_API, SERVICE_ACCOUNT_FILE,SERVICE_ACCOUNT_JSON,DELEGATED_USER,SCOPES, USER_ID,MAX_RETRIES}. The password (SMTP path) and service-account JSON (API path) are both env-only secrets — never hardcoded.

is_present

@classmethod
def is_present(prefix: str = 'EMAIL') -> bool

True when a Gmail mailbox is configured — drives backend auto-detect.

to_smtp_config

def to_smtp_config() -> SmtpConfig

Project the app-password path onto a generic :class:SmtpConfig.

GraphConfig

Bases: BaseModel

Microsoft Graph send config — app-only (client-credentials) OAuth2.

An Entra app registration holding the application Mail.Send permission trades client_id + client_secret for a short-lived bearer token, then sends the MIME message via /users/{sender}/sendMail. There is NO refresh token and NO token store to maintain — the token is re-minted on demand from its own lifetime (distinct from the delegated broker OAuth2 flows).

sender is the mailbox sent AS — e.g. a free shared mailbox reports@nullcapital.net. With application permissions, Send-As is not evaluated and the mailbox needs no license; scope the app to only this mailbox in Exchange (RBAC for Applications / ApplicationAccessPolicy).

from_env("EMAIL") reads EMAIL_GRAPH_{TENANT_ID,CLIENT_ID,CLIENT_SECRET,SENDER}. Switching the whole stack from SMTP to Graph is therefore a values change (these env keys present -> Graph), never a code change. Secrets are :class:SecretStr, env-sourced.

Fields and properties declared here; inherited members belong to the bases above.

authority

authority: str = Field(default=GRAPH_AUTHORITY, description='Microsoft identity authority host')

client_id

client_id: str = Field(description='Entra app registration (client) ID')

client_secret

client_secret: SecretStr = Field(description='App client secret (secret)')

graph_base

graph_base: str = Field(default=GRAPH_BASE_URL, description='Graph API base URL')

max_retries

max_retries: int = Field(default=3, ge=0, le=10, description='Retries for throttled/unavailable responses (429/503/504) only')

scope

scope: str = Field(default=GRAPH_DEFAULT_SCOPE, description='OAuth2 scope (app-only .default)')

send_url

Read-only property.

send_url: str

The sendMail endpoint for the sender mailbox.

sender

sender: str = Field(description='Mailbox to send AS / From address')

tenant_id

tenant_id: str = Field(description='Entra directory (tenant) ID')

timeout

timeout: float = Field(default=30.0, gt=0, description='HTTP timeout (seconds) for token + send')

token_url

Read-only property.

token_url: str

The client-credentials token endpoint for this tenant.

from_env

@classmethod
def from_env(prefix: str = 'EMAIL') -> GraphConfig

Build from {PREFIX}_GRAPH_{TENANT_ID,CLIENT_ID,CLIENT_SECRET,SENDER}.

All four are required (a missing one raises KeyError — we never silently default a credential or the sender mailbox).

is_present

@classmethod
def is_present(prefix: str = 'EMAIL') -> bool

True when the Graph creds are in the env — drives backend auto-detect.

ImapConfig

Bases: BaseModel

Inbound IMAP server configuration (the read side) — provider-neutral.

from_env("EMAIL") reads EMAIL_IMAP_HOST / _PORT / _USER / _PASSWORD / _USE_SSL. Host is required; port defaults to the standard 993.

Fields and properties declared here; inherited members belong to the bases above.

host

host: str = Field(description='IMAP server hostname (consumer-supplied)')

password

password: SecretStr = Field(description='Login password or app password (secret)')

port

port: int = Field(default=DEFAULT_IMAP_PORT, description='IMAP port (993 SSL, 143 plain)')

timeout

timeout: float = Field(default=30.0, description='Socket timeout (seconds) for the IMAP connection')

use_ssl

use_ssl: bool = Field(default=True, description='Connect with IMAP4_SSL')

user

user: str = Field(description='Login user / mailbox address')

from_env

@classmethod
def from_env(prefix: str = 'EMAIL') -> ImapConfig

Build from {PREFIX}_IMAP_{HOST,PORT,USER,PASSWORD,USE_SSL} env vars.

maybe_from_env

@classmethod
def maybe_from_env(prefix: str = 'EMAIL') -> Optional[ImapConfig]

Build only if {PREFIX}_IMAP_HOST is present; else None (send-only).

SmtpConfig

Bases: BaseModel

Outbound SMTP server configuration (the send side) — provider-neutral.

One shape for ANY SMTP server. from_env("EMAIL") reads EMAIL_SMTP_HOST / _PORT / _USER / _PASSWORD / _USE_TLS. The host is required (consumer-supplied — e.g. smtp.titan.email or smtp.gmail.com); only the port has a generic standard default (587). The password is always read from env, never hardcoded.

Fields and properties declared here; inherited members belong to the bases above.

host

host: str = Field(description='SMTP server hostname (consumer-supplied)')

implicit_tls

Read-only property.

implicit_tls: bool

True for SMTPS (port 465 or explicit use_ssl) — STARTTLS is then moot.

password

password: SecretStr = Field(description='Login password or app password (secret)')

port

port: int = Field(default=DEFAULT_SMTP_PORT, description='SMTP port (587 STARTTLS, 465 SSL, 25 plain)')

timeout

timeout: float = Field(default=30.0, gt=0, description='Socket timeout (seconds) for the SMTP connection')

use_ssl

use_ssl: Optional[bool] = Field(default=None, description='Implicit TLS from the first byte (SMTPS); None = only on port 465')

use_tls

use_tls: bool = Field(default=True, description='Issue STARTTLS after connecting')

user

user: str = Field(description='Login user / From address')

from_env

@classmethod
def from_env(prefix: str = 'EMAIL') -> SmtpConfig

Build from {PREFIX}_SMTP_{HOST,PORT,USER,PASSWORD,USE_TLS,USE_SSL,TIMEOUT}.

Host, user and password are required (one KeyError names every missing key — we never silently default a host or a credential); port falls back to 587, and port 465 selects implicit TLS unless USE_SSL says otherwise.

Types and values

DEFAULT_IMAP_PORT

DEFAULT_IMAP_PORT = 993

DEFAULT_SMTP_PORT

DEFAULT_SMTP_PORT = 587

GMAIL_FULL_SCOPE

GMAIL_FULL_SCOPE = 'https://mail.google.com/'

GMAIL_IMAP_HOST

GMAIL_IMAP_HOST = 'imap.gmail.com'

GMAIL_IMAP_PORT

GMAIL_IMAP_PORT = 993

GMAIL_MODIFY_SCOPE

GMAIL_MODIFY_SCOPE = 'https://www.googleapis.com/auth/gmail.modify'

GMAIL_SMTP_HOST

GMAIL_SMTP_HOST = 'smtp.gmail.com'

GMAIL_SMTP_PORT

GMAIL_SMTP_PORT = 587

GRAPH_AUTHORITY

GRAPH_AUTHORITY = 'https://login.microsoftonline.com'

GRAPH_BASE_URL

GRAPH_BASE_URL = 'https://graph.microsoft.com/v1.0'

GRAPH_DEFAULT_SCOPE

GRAPH_DEFAULT_SCOPE = 'https://graph.microsoft.com/.default'