# Submit mail through authorized connections

Compose SMTP and Graph sending, current authority, token sources and explicit outcomes.

Start with [configure outgoing email](/foundation/0.19.0/guides/mail-setup/) for the integration sequence.
This page is the detailed connection, token and delivery contract for 0.19.0.

## SMTP certificate policy

SMTP supports a per-connection certificate policy for development and internal
servers, including hosts outside loopback. The default remains strict validation.

| `SmtpOptions.CertificateValidation` | Behavior |
| --- | --- |
| `Strict` | Validate the certificate, hostname, chain and revocation status |
| `SkipRevocationCheck` | Disable revocation checking; retain hostname, trust and validity checks |
| `InsecureAcceptAny` | Accept any presented server certificate, including self-signed, expired or mismatched names |

```csharp
services.AddFabricatorsMail(options =>
{
    options.Host = "smtp.internal.example";
    options.Port = 587;
    options.Security = SmtpSecurity.StartTls;
    options.CertificateValidation = SmtpCertificateValidation.SkipRevocationCheck;
});
```

For an untrusted/self-signed certificate, select `InsecureAcceptAny` explicitly
instead. Encryption is still required by `StartTls`/`Tls`; certificate identity
checking is what this option relaxes. It does not enable cleartext transport.
`SkipRevocationCheck` is the narrower setting when only `RevocationStatusUnknown`
prevents an otherwise valid chain from being accepted.

Connected mail copies this policy from the trusted
`ISmtpConnectionSettingsSource` snapshot. Products own authorization to configure
it; it is not an argument supplied by an email sender or an untrusted API caller.
The setting belongs to one SMTP client and does not change process-global TLS,
other mail profiles, Graph or OIDC. Unknown enum values fail configuration.

Real loopback TLS acceptance tests cover STARTTLS and implicit TLS with an expired,
wrong-host, self-signed certificate: strict/revocation-only reject before SMTP
authentication; explicit insecure mode submits mail; a later strict connection
still rejects it. An SMTP server without STARTTLS cannot trigger a downgrade.

Status: supplied in **0.8.0**. The published 0.7.1
packages retain their original APIs. This increment supplies sending and future
reading contracts; it does not implement incoming synchronization, attachments,
webhooks, OAuth consent UI or product credential persistence.

## Packages and compatibility

- `Fabricators.Application` owns provider-free connection, token-source, submission
  and future reader ports. Existing OutgoingMail/MailSubmission constructors and
  deconstruction shapes remain unchanged. Optional Cc/Bcc/ReplyTo, InReplyTo and
  References use init properties. OutgoingMail.ToString is redacted.
- `Fabricators.Mailing` supplies dispatch and common bounded MIME composition,
  reusing MimeKit 4.16 already present through MailKit. It has no EF/web dependency.
- `Fabricators.Mailing.MailKit` retains the configured IMailTransport and adds a
  connection-bound SMTP provider, including password, anonymous and SASL XOAUTH2.
- `Fabricators.Mailing.MicrosoftGraph` adds Graph MIME submission using .NET HTTP
  primitives and the same composer; it does not pull in the SMTP adapter or Graph SDK.

Current submission bounds are 50 total To/Cc/Bcc recipients, 10 ReplyTo addresses,
50 References, 200 characters per message/thread ID and 500 subject characters.
The published 0.16.0 adapter also limits each text/HTML body to 1 Mi characters;
version 0.17.0 replaces that bound with the byte policy below.
Header/address controls and default immutable collections
are rejected before external submission. No arbitrary headers or attachments are accepted.
SMTP keeps blind recipients in its envelope without exposing a Bcc wire header;
Graph receives the Bcc MIME header for its own recipient processing. Bcc is not
included in incoming/public projections. Exact mailbox addresses in AllowedSenders
are compared ordinally after MIME address parsing; supply canonical approved aliases.

## Rendering and message size policy

Status: **supplied in 0.17.0**, not included in 0.16.0.
Rendering is optional and independent of sending. `TemplateRenderOptions`
controls source, JSON model and output **characters**, plus loop iterations.
Defaults remain 65,536 / 1,048,576 / 1,048,576 characters and 10,000 iterations.
Trusted hosts may raise or lower these positive `int` budgets without the former
fixed upper ceilings. The renderer snapshots them when created; no request may
select its own budgets. These are resource guards, not email provider limits.

Both `SmtpOptions.MaximumMimeBytes` and `GraphMailOptions.MaximumMimeBytes`
default to **10,485,760 bytes (10 MiB)**. They count the complete serialized MIME:
headers, UTF-8/transfer encoding, multipart boundaries, bodies and CRLFs.
The transport counts without buffering the whole message, before submitting it.
`MailMessageComposer.Create` only composes MIME; it does not enforce transport
policy. The transport's final representation is the source of truth, not the
body's character count or the renderer's output budget.

```csharp
services.AddFabricatorsTemplates(
    configure: _ => { },
    configureRendering: options =>
    {
        options.MaximumModelCharacters = 8 * 1024 * 1024;
        options.MaximumOutputCharacters = 4 * 1024 * 1024;
    });
services.AddFabricatorsMail(options =>
{
    options.Host = "smtp.example.test";
    options.MaximumMimeBytes = 20L * 1024 * 1024;
});
```

`MailConnection.MaximumMimeBytes` is an optional trusted connection bound. It can
only tighten the transport's configured limit, never raise it. It is part of the
authority/revision snapshot and must be revalidated like every other field.
Connected SMTP obtains fresh trusted `SmtpOptions` per operation without restarting;
Graph transport options are snapshotted per transport instance. Changing a runtime
connection policy requires updating its authoritative revision.

SMTP enforces the smallest of host, connection and positive server-advertised
`SIZE`, using capabilities available after TLS/authentication. It measures the
MailKit-prepared representation before `MAIL FROM`, including when the server
omits `SIZE` or advertises zero. SMTP dot-stuffing/terminator are protocol framing,
not part of the MIME SIZE count. The server may enforce a stricter unadvertised
mailbox policy; a rejection remains authoritative and causes no automatic retry.

Graph sends the complete MIME as Base64 in a `text/plain` HTTP request.
`GraphMailOptions.MaximumRequestBytes` defaults to **4,000,000 bytes** and may
only be lowered: this adapter conservatively bounds the documented 4 MB Graph
write-request ceiling. It separately checks `4 * ceil(mimeBytes / 3)` before
requesting a token or sending HTTP. Raising the MIME budget cannot bypass this
provider bound. A Graph HTTP 413 is classified as `MessageTooLarge`; it does not
imply a discoverable numeric mailbox limit. Provider acceptance is still subject
to mailbox/tenant policy; Foundation does not infer quota changes or delivery.

Local size rejection is `MailSubmissionException` with
`Failure = MailFailure.MessageTooLarge` and `SizeViolation`: limit kind, maximum
bytes and observed minimum bytes. Counting can stop at the first excess, so the
last value is a lower bound, not necessarily the entire message length. No body,
credentials, addresses or provider response are included. Equality is accepted;
zero/negative configured limits fail validation. Neither transport automatically
splits, truncates, retries, changes providers or sends an alternate message.

Foundation supplies sending tools. Consumer applications own campaigns, lists,
consent, unsubscribe links/text, recipient eligibility, queue persistence, pacing,
provider throughput quotas and retry/reconciliation. No queue or pacing service
is added. The existing explicitly invoked `TemplateBatchComposer` remains a
composition helper for consumers that choose it; sending never invokes it.

Provider references: [Graph request size limits](https://learn.microsoft.com/en-us/graph/use-the-api)
and [Graph MIME submission](https://learn.microsoft.com/en-us/graph/outlook-send-mime-message).

## Product authority and credentials

Register `AddFabricatorsConnectedSmtp` and/or `AddFabricatorsGraphMail`, then resolve
`IConnectedMailTransport` inside the product's authorized execution scope. Its
SubmitAsync receives an opaque connection selector and an OutgoingMail request.
Unknown/denied selectors return Unavailable. Duplicate provider registration fails
instead of choosing an arbitrary provider.

The host must supply `IMailConnectionAuthority`. ResolveAsync binds the caller and
capability to current connection data. EnsureCurrentAsync must revalidate **all**
snapshot fields, revision, enabled state and current caller grants immediately before
network submission. Checking an ID without validating a forged mailbox/sender/grant
snapshot does not satisfy this contract. Neither client input nor the DTO is proof.
No allow-all authority or credential implementation is shipped.

Connection protocol, service/user ownership and delegated/application authorization
are independent fields. Graph requires an OAuth mode and a trusted selected mailbox.
It does not automatically send from /me or infer a mailbox from product login.
The current adapter selects /users/{mailbox}/sendMail, including for delegated grants;
the configured provider grant must authorize that exact mailbox and sender alias.
Keep identity login scopes/grants separate from mailbox authorization.

SMTP needs `ISmtpConnectionSettingsSource`, which returns runtime settings bound to
the exact connection snapshot. Password mode requires username/password; anonymous
mode rejects configured password credentials. OAuth mode uses a separate OAuthUsername
and `IMailAccessTokenSource`; password authentication is never a silent fallback.
The old deployment-level AddFabricatorsMail/IMailTransport path remains available
for already authorized system-mail callers.

Graph requires `IMailAccessTokenSource`; SMTP requires it only for OAuth. It must
acquire/cache tokens through the host's trusted OAuth implementation, serialize refresh,
protect persistence, recheck scopes/audience and fence disconnects. Foundation does
not implement MSAL acquisition, a refresh-token database or a consent callback here.
MailAccessToken is runtime-only, redacts ToString, and does not serialize its bearer
value. Its lease is bound to connection ID, revision, audience and an expiry at least
30 seconds away. Do not accept a lease or connection snapshot from a public API.

The Graph adapter is scoped, so user/tenant authorities and token sources cannot
become singleton-captured state. Its pooled socket handler carries no default bearer
header or cookies; authorization is assigned per request. Resolve service ports from
a scope, including in background workers, and dispose scopes/transports correctly.

## Endpoint, TLS and error behavior

GraphMailOptions defaults to `https://graph.microsoft.com/v1.0/`, with a bounded
10-second timeout. Arbitrary remote origins, URI credentials/query/fragment and
other paths are rejected. Only an explicit numeric HTTP loopback override supports
controlled fixtures. National-cloud endpoints are not implemented by this profile.
Redirects are disabled. Errors never include provider bodies, bearer values or raw
SMTP replies. Standard TLS certificate validation is the default.

Required STARTTLS and implicit TLS do not downgrade automatically. Cleartext to a
named relay requires the explicit UnencryptedTrustedRelay policy; credentials
over cleartext require their own explicit opt-in. Numeric loopback has a separate
test mode. Per-connection certificate relaxation is available as documented above;
it does not disable validation globally. See [host compatibility](/foundation/0.19.0/guides/host-compatibility/).

Both adapters return MailSubmission only after SMTP acceptance or Graph HTTP 202.
The logical MessageId is not a delivery receipt, provider object ID or deduplication
key. Graph's optional ProviderRequestId is request correlation only.

Connected transports classify failure as Unavailable, InvalidConfiguration,
AuthenticationRequired, AccessDenied, Throttled, Rejected or UnknownOutcome.
Version 0.17.0 adds the explicit `MessageTooLarge` outcome described above.
Graph 401/403/429 preserve authentication/authorization/throttling distinctions;
ordinary 4xx rejection is explicit, while 408/5xx and network failure after entering
submission remain conservatively uncertain. Retry-After supports delta/date forms,
bounded to 0–24 hours. No status causes an automatic retry or reauthentication replay.
SMTP command rejection has a known negative outcome; a dropped response after DATA
is UnknownOutcome. Cancellation after external submission starts also cannot prove
that no message was sent. Preserve that outcome with a non-cancelled cleanup workflow.

Rechecking grants cannot atomically cancel already in-flight SMTP/Graph processing.
Products must own durable outbox intents, audit, retry/reconciliation and disclosure
of ambiguous outcomes. SMTP/Graph cannot join the product DB transaction or promise
exactly-once delivery. No network call is performed merely by service registration.

## Reader contracts only

`IMailboxReader`, folder/message DTOs, provider item keys and page/cursor records are
provided without a default reader implementation. There is no background poller,
message store, cursor advancement, attachment downloader or webhook subscription.
Future readers must authorize Read/folder scope, bound page size and bytes, avoid
implicit read/move/delete mutations and validate continuation origins before using
credentials. Persist imported data/receipts before advancing NextPage or Checkpoint.

Graph keys must request immutable IDs; IMAP keys need UIDVALIDITY in Epoch plus UID
in ProviderItemId, with mailbox/folder scoping. InternetMessageId is descriptive,
not a deduplication authority. Bodies/HTML/attachments remain untrusted. Cursor and
incoming-message ToString output is redacted; products still protect storage/DTO access.

## Verification boundaries

Real loopback SMTP tests cover old API compatibility, rich envelopes, password and
XOAUTH2, rejection and response loss. Graph tests use actual HTTP requests and MIME
parsing for delegated/application modes, authority/token isolation, revocation before
I/O, redirects, status classification, throttling and ambiguous cancellation/disconnect.
Independent packed consumers compile/run the new provider and provider-free reader
contracts. Existing session/MFA/PostgreSQL suites remain required regression gates.
No live mailbox/provider registration or delivery-to-recipient claim is made.

Protocol references: [Graph sendMail](https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0)
and [Graph throttling](https://learn.microsoft.com/en-us/graph/throttling).
