Skip to content

common_reports.emails.client

EmailClient — the high-level, ergonomic front door.

Composes a :class:CoreEmailClient (the engine) over a concrete provider, and exposes the friendly factories + a keyword send that builds the :class:EmailMessage for you. Multi-domain ready: the config (env prefix / explicit params) decides the domain, never the code.

Construction: EmailClient.from_env(prefix=“EMAIL”) # EMAIL_SMTP_* (+ optional EMAIL_IMAP_*) EmailClient.from_smtp(host, port, user, password, …) EmailClient.from_gmail(user, app_password=…) | from_gmail(…, use_api=True, …) EmailClient.from_provider(provider, …) # bring your own BaseProvider

Send: client.send(to, subject, html=…, attachments=…, cc=…, bcc=…) -> SendResult client.send_message(EmailMessage) -> SendResult await client.asend(…)

Read: client.read(folder=“INBOX”, limit=10, unseen_only=False) -> ReadBatch client.inbox(limit=10)

Lifecycle: client.close() / await client.aclose(), or with / async with the client: releases the provider’s held transports (the Gmail API keeps one per thread).

Classes

EmailClient

Read-write email client — thin wrapper over the engine + a provider.

__init__

def __init__(engine: CoreEmailClient)

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

context

Read-only property.

context: EmailContext

logger

logger = engine.logger

provider

Read-only property.

provider: BaseProvider

The underlying transport provider.

aclose

async def aclose() -> None

acreate_draft_message

async def acreate_draft_message(request: DraftRequest) -> DraftResult

acreate_label

async def acreate_label(request: LabelCreateRequest | str) -> LabelBatch

adelete_draft

async def adelete_draft(draft_id: str) -> MutationResult

adelete_label

async def adelete_label(label_id: str) -> MutationResult

adraft_reply_message

async def adraft_reply_message(request: ReplyRequest) -> DraftResult

aget_attachment

async def aget_attachment(message_id: str, attachment_id: str) -> AttachmentResult

aget_message

async def aget_message(message_id: str) -> MessageResult

aget_profile

async def aget_profile() -> ProfileResult

aget_thread

async def aget_thread(thread_id: str) -> ThreadResult

alist_history

async def alist_history(query: HistoryQuery | str, **options) -> HistoryResult

alist_labels

async def alist_labels() -> LabelBatch

alist_message_refs

async def alist_message_refs(query: Optional[MessageQuery] = None, **filters) -> MessageRefBatch

alist_thread_refs

async def alist_thread_refs(query: Optional[MessageQuery] = None, **filters) -> ThreadRefBatch

amodify_labels

async def amodify_labels(update: LabelUpdate) -> MutationResult

areply_message

async def areply_message(request: ReplyRequest) -> SendResult

asearch

async def asearch(query: Optional[MessageQuery] = None, **filters) -> MessageBatch

asend

async def asend(to: RecipientsLike = None, subject: str = '', html: str = '', text: Optional[str] = None, cc: RecipientsLike = None, bcc: RecipientsLike = None, attachments: Union[bool, str, list, tuple, Iterable[AttachmentLike], None] = None, reply_to: Optional[str] = None, headers: Optional[dict] = None, message_id: Optional[str] = None, disclose_recipients: bool = False) -> SendResult

Async send.

asend_draft

async def asend_draft(draft_id: str) -> DraftResult

astop_watch

async def astop_watch() -> MutationResult

awatch

async def awatch(request: WatchRequest | str, **options) -> WatchResult

capability_report

def capability_report() -> CapabilityResult

Report the exact operations this configured provider supports.

close

def close() -> None

Release what the provider holds between calls (the Gmail API’s open transports). A later call opens fresh ones. Close after calls finish.

create_draft

def create_draft(*, to: RecipientsLike = None, subject: str = '', html: str = '', text: Optional[str] = None, cc: RecipientsLike = None, bcc: RecipientsLike = None, attachments: Union[bool, str, list, tuple, Iterable[AttachmentLike], None] = None, thread_id: Optional[str] = None, in_reply_to: Optional[str] = None, references: tuple[str, ...] = ()) -> DraftResult

create_draft_message

def create_draft_message(request: DraftRequest) -> DraftResult

create_label

def create_label(request: LabelCreateRequest | str) -> LabelBatch

delete_draft

def delete_draft(draft_id: str) -> MutationResult

delete_label

def delete_label(label_id: str) -> MutationResult

draft_reply

def draft_reply(message_id: str, *, to: RecipientsLike = None, subject: str = '', html: str = '', text: Optional[str] = None, cc: RecipientsLike = None, bcc: RecipientsLike = None, attachments: Union[bool, str, list, tuple, Iterable[AttachmentLike], None] = None, reply_all: bool = False, thread_id: Optional[str] = None) -> DraftResult

Ergonomic reply draft, addressed and threaded exactly as :meth:reply sends.

draft_reply_message

def draft_reply_message(request: ReplyRequest) -> DraftResult

Save a reply as a draft using a fully validated request; nothing is sent.

from_config

@classmethod
def from_config(smtp: Optional[SmtpConfig] = None, gmail: Optional[GmailConfig] = None, graph: Optional[GraphConfig] = None, imap: Optional[ImapConfig] = None, context: Optional[EmailContext] = None, name: str = 'default') -> EmailClient

Build from already-constructed config schemas (SMTP / Gmail / Graph).

from_env

@classmethod
def from_env(prefix: str = 'EMAIL', backend: Optional[str] = None, context: Optional[EmailContext] = None, name: Optional[str] = None) -> EmailClient

Build a client entirely from env vars under {prefix}_.

backend resolves in this order: an explicit arg > the {prefix}_BACKEND env var (smtp / gmail / graph; auto/unset = detect) > AUTO-DETECT (Graph if {prefix}_GRAPH_* creds are present — reads {prefix}_GRAPH_{TENANT_ID,CLIENT_ID,CLIENT_SECRET,SENDER} — else Gmail if {prefix}_GMAIL_USER is set, else SMTP, {prefix}_SMTP_* + optional {prefix}_IMAP_*). The env override lets a deployment pick a backend even when other creds are present — {prefix}_BACKEND=gmail is the whole switch once {prefix}_GMAIL_* is in place.

When no context is passed, account defaults are layered from env too (all optional): {prefix}_FROM (or {prefix}_SMTP_SENDER fallback) as the From address, {prefix}_FROM_NAME as the From display name, and {prefix}_REPLY_TO as the default Reply-To. This is what lets a transport whose login user is not a valid From (e.g. ACS SMTP) still send as reports@… with a "Null Capital Reports" display name — purely via values.

Switching providers / senders is therefore a values change, no code change.

from_gmail

@classmethod
def from_gmail(user: str, app_password: Optional[str] = None, use_api: bool = False, service_account_file: Optional[str] = None, service_account_json: Optional[str] = None, delegated_user: Optional[str] = None, scopes: Optional[tuple[str, ...]] = None, user_id: str = 'me', max_retries: int = 3, imap: Optional[ImapConfig] = None, context: Optional[EmailContext] = None, name: str = 'gmail') -> EmailClient

Build a Gmail client — app-password SMTP (default) or the Gmail API.

from_graph

@classmethod
def from_graph(tenant_id: str, client_id: str, client_secret: str, sender: str, context: Optional[EmailContext] = None, name: str = 'graph') -> EmailClient

Build a Microsoft Graph client (app-only OAuth2) from raw params.

sender is the mailbox sent AS (e.g. a free shared mailbox reports@nullcapital.net). The secret is a plain str only to coerce into a :class:~pydantic.SecretStr — pass an env-sourced value, never a literal.

from_provider

@classmethod
def from_provider(provider: BaseProvider, login_user: str = '', context: Optional[EmailContext] = None, name: str = 'default') -> EmailClient

Build over an arbitrary :class:BaseProvider (the low-level door).

from_smtp

@classmethod
def from_smtp(host: str, user: str, password: str, port: int = SmtpConfig.model_fields['port'].default, use_tls: bool = True, imap: Optional[ImapConfig] = None, context: Optional[EmailContext] = None, name: str = 'default') -> EmailClient

Build a send-first SMTP client from raw params.

host is required (provider-neutral — pass smtp.titan.email or smtp.gmail.com). The password is a plain str only to coerce into a :class:SecretStr — callers should pass an env-sourced value, never a literal.

get_attachment

def get_attachment(message_id: str, attachment_id: str) -> AttachmentResult

get_message

def get_message(message_id: str) -> MessageResult

get_profile

def get_profile() -> ProfileResult

get_thread

def get_thread(thread_id: str) -> ThreadResult

inbox

def inbox(limit: int = 10, unseen_only: bool = False) -> ReadBatch

Convenience: read the INBOX.

list_history

def list_history(query: HistoryQuery | str, **options) -> HistoryResult

list_labels

def list_labels() -> LabelBatch

list_message_refs

def list_message_refs(query: Optional[MessageQuery] = None, **filters) -> MessageRefBatch

One page of the messages a search matches, by identity; nothing is fetched.

list_thread_refs

def list_thread_refs(query: Optional[MessageQuery] = None, **filters) -> ThreadRefBatch

One page of the threads a search matches, by identity; nothing is fetched.

mark_read

def mark_read(target_ids: list[str], *, target_kind: Literal['message', 'thread'] = 'message') -> MutationResult

mark_unread

def mark_unread(target_ids: list[str], *, target_kind: Literal['message', 'thread'] = 'message') -> MutationResult

modify_labels

def modify_labels(update: LabelUpdate) -> MutationResult

read

def read(folder: str = 'INBOX', limit: int = 10, unseen_only: bool = False) -> ReadBatch

Read messages from a folder.

reply

def reply(message_id: str, *, to: RecipientsLike = None, subject: str = '', html: str = '', text: Optional[str] = None, cc: RecipientsLike = None, bcc: RecipientsLike = None, attachments: Union[bool, str, list, tuple, Iterable[AttachmentLike], None] = None, reply_all: bool = False, thread_id: Optional[str] = None) -> SendResult

Ergonomic reply; omitted recipients are derived from the original.

reply_message

def reply_message(request: ReplyRequest) -> SendResult

Reply using a fully validated request.

def search(query: Optional[MessageQuery] = None, **filters) -> MessageBatch

Search messages and return normalized records with pagination.

send

def send(to: RecipientsLike = None, subject: str = '', html: str = '', text: Optional[str] = None, cc: RecipientsLike = None, bcc: RecipientsLike = None, attachments: Union[bool, str, list, tuple, Iterable[AttachmentLike], None] = None, reply_to: Optional[str] = None, headers: Optional[dict] = None, message_id: Optional[str] = None, disclose_recipients: bool = False) -> SendResult

Send a message. Keyword front door over EmailMessage + the engine.

attachments accepts the AlgoReports spec (True -> all cwd *.html; a dir / filename-prefix str; or a list of paths / (name, bytes) tuples / :class:Attachment, including Attachment.inline_image parts referenced as cid:).

Recipients are private by default (no To/Cc header — nobody sees the list); disclose_recipients=True writes visible To/Cc. message_id pins a caller-owned RFC Message-ID (an idempotency key). Never raises: failures return SendResult(success=False, error=..., error_type=...).

send_draft

def send_draft(draft_id: str) -> DraftResult

send_message

def send_message(msg: EmailMessage) -> SendResult

Send a pre-built :class:EmailMessage.

stop_watch

def stop_watch() -> MutationResult

watch

def watch(request: WatchRequest | str, **options) -> WatchResult