Skip to content

Email

Fullfinity has a complete email stack built into core: Jinja-rendered email templates (optionally with an auto-attached PDF report), an outbound queue with retry and open/click tracking, inbound routing that turns incoming mail into records, and configurable IMAP/SMTP servers. This page covers each piece and the exact APIs.

An EmailTemplate is a data record holding a Jinja subject and body, bound to a model. When rendered, the template is given a serialized instance of that model as its context, so any field on the record is available as a Jinja variable.

modules/invoicing/data/email_templates.yaml
- depends:
- ../templates/report_templates.yaml
data_type: EmailTemplate
identifier: financial_document_send_template
name: Send Financial Document
subject: '{{ type }} {{ number }} from {{ company.name }}'
content: ../templates/email_financial_document.jinja
model: FinancialDocument
module: invoicing
report: financial_document_print
apply_once: true
FieldTypeMeaning
identifierCharStable handle used to look the template up in code.
nameCharHuman-readable label.
subjectCharJinja string rendered against the record.
contentTextJinja body. In YAML you point at a .jinja file (loaded as the field value).
modelManyToOne (ModelRegistry)The model the template renders against.
reportManyToOne (ReportAction)Optional. A report to generate as a PDF and attach to the email.
attachmentsManyToMany (Attachment)Optional static attachments.
from_email / to_email / cc_email / reply_emailCharOptional default addressing.

send_document renders the template for one record and queues it, with the template’s report attached:

await template.send_document("SaleOrder", order.id, to_emails=[email], company=order.company,
contact=order.contact)

The PDF is rendered when the email is delivered, not when it is queued. A document emailed in the request that created it (a shop checkout confirms the order and sends it at once) only gets its number as that request ends; rendered earlier, its PDF would carry a placeholder instead. The subject and body are rendered straight away. The PDF is filed on the record and rendered in the recipient’s language. With send_immediately=True the email leaves once the request’s document numbers are issued.

Look the template up by its identifier and call render_template:

EmailTemplate = get_model("EmailTemplate")
template = await EmailTemplate.filter(identifier="financial_document_send_template").first()
rendered = await template.render_template(template, "FinancialDocument", document.id)
# rendered == {"subject": "...", "content": "..."}

render_template(self, email_template, class_name, instance_id, extra_context=None, recipient=None) fetches the instance (with all its relational fields prefetched), serializes it, and renders the subject and body. extra_context adds names the template can use beyond the record’s own fields. The Jinja environment is enriched with:

  • a date filter that respects the recipient’s locale date format,
  • a money filter ({{ amount | money }}) using the record’s company currency,
  • a t(...) translation function plus automatic translation of the rendered output into the recipient’s language (resolved from the contact’s, then the current user’s, language).

The recipient is the record’s contact field. When your model keeps the person it writes to under another name — an event registration’s attendee, a booking’s customer — pass that Contact as recipient=, or the email comes out in the language of whoever triggered the send:

rendered = await template.render_template(
template, "Registration", registration.id,
extra_context={"badge_url": badge_url}, recipient=registration.attendee,
)

Unlike a report template, an email body is not an extension surface: there is no inheriting EmailTemplate and no {% add %}/{% replace %} patching. A template is one document owned by the module that ships it and edited directly. An add-on that needs a different email ships its own EmailTemplate and sends that one.

Email, SMS and WhatsApp share one outbound layer on the Message table — there is no separate “email queue” table. A queued send is simply a Message row with send_state="Queued" and direction="Outbound". A single cron drains it.

Message.queue_email(...) is the producer. Its signature:

await get_model("Message").queue_email(
author, # User instance (sender); its contact's email becomes From
contact_emails, # list[str] of recipient addresses
subject, # str
body, # str (HTML)
attachments=None, # list[Attachment]
tracking_identifier=None, # str; enables open/click tracking + reply threading
*,
layout, # REQUIRED: "Personal", "Branded" or "Custom Design" (see below)
company=None, # Company for branding
message=None, # an existing collaboration Message to reuse as the send job
scheduled_at=None, # delay sending until this time (defaults to now)
model=None, # the model this email is about, e.g. "SaleOrder"
document=None, # that record's id
contacts=None, # recipient Contact records/ids
)

Every send names how the email is dressed, by who is speaking. layout has no default: leave it out and the call raises, because a default is how a person’s one-line reply ends up framed like a newsletter.

layoutUse it forWhat the recipient gets
"Personal"A person writing to a person: a reply typed on a record, an agent answering a ticket, an internal alertA plain email, like one sent from a mail client: the text and the sender’s signature. No banner, no card, no footer.
"Branded"A document or system email: a quote, an invoice, an order confirmation, an invitation, a password reset, a reminderThe body on a white card under the company’s logo (or name), with a thin accent rule in the brand colour, and the company’s address in small type beneath the card.
"Custom Design"A body that is already a finished design, such as a marketing campaignThe body exactly as written. Nothing is added, not even a signature.

Why Personal is plain: heavy branded HTML on a one-to-one email reads as a form letter, Gmail tends to file it under Promotions, and every reply quotes the whole frame back, nesting card inside card. The Send dialog on a record picks for you: an email sent from a document template (Send Quote, Send Invoice) goes out Branded, and one typed by hand goes out Personal. Message.create_message(...) defaults to "Personal", since posting to a record’s thread is a person writing; pass layout="Branded" when it posts a system notice that emails its recipients.

The layout is stored on the message as email_layout and shown on the queue’s Options tab.

If you pass an existing message, that collaboration row becomes the queued send (one row is both the timeline entry and the send job). Otherwise a standalone email Message is created.

Anchor a programmatic send with model/document. A send raised from a form carries them for free; one raised in code has no form behind it. Anchoring is what lets the delivery add a portal link for the record (see Portal links below), and it files the mail on the record’s timeline. contacts names who was written to, which the delivery reads to translate the chrome it adds into the reader’s language.

There is also a higher-level helper, OutgoingMailServer.send_email(...), which queues by default and can send immediately with send_immediately=True:

await get_model("OutgoingMailServer").send_email(
author=contact, # Contact instance of the sender
contact_emails=["a@b.com"],
subject="Hello",
body="<p>Hi</p>",
attachments=[],
tracking_identifier="abc123",
layout="Branded", # required — see "Choosing a layout"
company=company,
message=None,
send_immediately=False, # True bypasses the queue and sends inline
model="SaleOrder", # the record this email is about
document=order.id,
contacts=[order.contact],
)

Queued messages are sent by a cron that calls Message.cron_flush():

async def cron_flush(cls):
"""Send queued messages that are due, and retry failed ones whose backoff elapsed."""

It selects up to 100 outbound rows that are Queued (and due, per scheduled_at) or Failed with an elapsed next_retry_at, oldest first, and calls send_now() on each. The cron entry itself ships in core — see the Cron / Scheduled Jobs page:

- data_type: CronJob
identifier: cron_message_queue_processor
name: Process Outbound Messages
model: Message
method: cron_flush
frequency: 1
frequency_unit: Minutes
active: true

send_now() flips the row through Sending → Sent (recording sent_at), dispatching the actual delivery by channel (_deliver_email for email, which builds the final body — signature, tracking pixel, link wrapping applied transiently — and hands off to SMTP). On failure it calls _mark_failed, which:

  • increments retry_count,
  • sets send_state="Failed",
  • schedules next_retry_at with a linear backoff of 5 × retry_count minutes, until max_retries (default 3) is reached, after which next_retry_at is left null.

To re-queue a failed message manually, call await message.action_retry() (resets the retry counter and sets it back to Queued); the cron picks it up on its next run.

Just before delivery, send_now() asks the message await self._withhold_reason(). A non-empty answer stops the send: the row becomes send_state="Withheld" with the answer in withheld_reason. Withheld is terminal — it is not a failure, the cron never picks it up again, and action_retry() does not re-queue it.

This is how consent given or withdrawn after a message was queued is honoured — a staggered campaign row or a scheduled automation step can wait hours. The shipped rules:

  • Campaigns withhold a campaign’s own message (any channel) when the recipient has since joined the suppression list, or opted out of every list the campaign targets. The campaign’s recipient is counted as Suppressed, not Sent or Failed. Email no campaign sent (invoices, password resets) is not withheld for an unsubscribe.
  • SMS / WhatsApp to a number on the suppression list (a STOP reply) is withheld for every message, transactional included, because carriers block all traffic from the sender to an opted-out number until it replies START.

Two more ways a message ends up Withheld:

  • The transport says the recipient opted out. A delivery hook may return {"withheld_reason": "…"} instead of the values to record; the message is then Withheld, not Failed. A messaging provider gets there by returning status: "Opted Out" from send_message (Twilio does for error 21610, a STOP sent to the carrier), and the number is added to the suppression list so the next message is withheld before it is attempted. Return "Failed" for a refusal that may clear (a rate or engagement limit): that one is retried.
  • The campaign was cancelled. Its still-queued messages are Withheld with the reason “Campaign cancelled”, and their recipients read Cancelled.

To add your own rule, extend Message and return a short, user-readable reason. The answer is final, so use it for “must never go”, not “not yet” (delay a send with scheduled_at instead). Call super() first and return its reason when it has one, so other modules’ rules still apply:

class MyMessage(Model):
__inherit__ = "Message"
async def _withhold_reason(self):
reason = await super()._withhold_reason()
if reason:
return reason
if self.delivery_channel == "SMS" and await self._on_do_not_text_register():
return t("This number is on the do-not-text register.")
return None

Tracking is keyed on the message’s tracking_identifier. When that is set and the install knows its public URL (see The install’s public URL), at send time the email body is rewritten to:

  • include a 1×1 tracking pixel pointing at /api/email/track/open/<tracking_id>, and
  • wrap every href so it routes through /api/email/track/click/<tracking_id>?url=....

These public routes record open_count / opened_at and click_count / clicked_at on the Message row. Each wrapped link also carries a signature of its address (&sig=), and the click route redirects only when it matches — so the route cannot be used to send someone to an arbitrary site under your domain. A link without a valid signature (altered, or from an email sent before links were signed) shows a page naming where it leads instead of redirecting silently.

A queue-stats endpoint (/api/email/queue/stats) is also provided.

Providers that report bounces by webhook (SendGrid, Mailgun, Amazon SES, or a generic {"tracking_id": …, "reason": …} body) post to /api/email/webhook/bounce. The endpoint requires the database’s token in the address and answers 401 without it. Copy the full address, token included, from Bounce Webhook Address on any Outgoing Mail Server form into the provider’s webhook settings. The token is derived from the install’s SECRET_KEY, so it changes if that key does: update the provider’s webhook then.

An EmailRoute turns an incoming email sent to a given alias into a new record in a target model, logging the email as that record’s first collaboration message. It routes only new inbound emails — replies are threaded onto existing records automatically by tracking id.

FieldTypeMeaning
addressCharLocal-part of the inbound address, e.g. leads for leads@yourdomain.
target_modelManyToOne (ModelRegistry)The model a record is created in, picked from the model registry (its label is what the form and list show). Junction tables and transient models are not offered and are refused on write.
target_name_fieldCharText field (Char/Text) on the target that receives the email subject (default name); chosen from that model’s fields, and refused if it is not one.
defaultsJSONDefault field values for created records. Every key must be a field of the target model — an unknown one is refused on save.
read_attachmentsBooleanHand the whole email to the target model’s create_from_email instead of creating a record from the subject.
companyManyToOne (Company)Owning company.
activeBooleanWhether the route is live.
working_addressesText (calculated)The addresses the route receives at, from the companies’ email domains.
managed_byChar (read-only)The record whose Email Alias this route belongs to (written by sync_alias); change the alias there.
conflictChar (calculated)Why the route will not receive mail it is written for: a duplicate that never receives, or two companies whose mail cannot be told apart because neither lists its domains.

Code that creates a route passes the registry record, looked up by class name:

ticket_model = await get_model("ModelRegistry").filter(name="HelpdeskTicket").get()
await get_model("EmailRoute").create(address="support", target_model=ticket_model.id)

EmailRoute.route_inbound(recipients, sender_email, subject, body) finds the first active route whose address matches a recipient’s local-part, creates the target record (populating common fields like email_from / email / description / company when the target model has them), and logs the inbound email as a Message on the new record.

Helpdesk teams, projects, sales teams and job positions each carry an Email Alias — a route maintained for the record: mail to it creates a ticket, task, lead or applicant linked to it. Give your own model one by declaring the two fields and syncing on write:

email_alias = Char(max_length=100, description="Email Alias")
email_route = ManyToOne("EmailRoute", related_name="my_things", on_delete="SET NULL")
async def update(cls, records, **vals):
result = await super().update(records, **vals)
if "email_alias" in vals:
for owner in records:
await get_model("EmailRoute").sync_alias(owner, "MyTicket", {"thing": owner.id})
return result

sync_alias(owner, target, defaults, name_field="name", read_attachments=False) creates or updates the route under the owner’s company, and deactivates it when the alias is cleared. With read_attachments=True the target model’s own create_from_email reads the mail (an applicant is named after the sender, not the subject); such a reader files the email on the record it built with EmailRoute.file_email(model_name, record_id, sender_email, subject, body, attachments) — logged as the first message, attachments kept — exactly as a standard route does.

Each company lists the domains it receives email at (CompanyEmailDomain, on the company form). The recipient’s domain decides whose mail it is:

  • a company’s bare route (support) takes mail for its own domains only;
  • a company that lists no domain takes mail for any domain no other company has claimed — so an install that lists none routes as before;
  • a shared route (no company) creates its record as the company that lists the recipient’s domain;
  • a full-address route (support@acme.com) matches that address alone, as before.

A domain belongs to one company and is stored lowercase. Two companies with a support route that both list no domains still cannot be told apart, and such mail is left unread for a person.

Incoming and outgoing servers are configured as records, with SMTP falling back to global config. Each server has an auth_type that selects how it authenticates:

  • Password (default) — Basic Auth with username + password, over SMTPS/IMAPS or, on a non-SSL port, STARTTLS whenever the server offers it (with certificate verification). If the server offers no encryption at all, the login is refused rather than sending the password in clear — unless the record turns on allow_unencrypted_login (a relay on a trusted network). A server needing no login (an internal relay on port 25) is unaffected. A blank port means the standard one: 465/587 for SMTP, 993/143 for IMAP, by use_ssl. Use this for any standard relay: your own mail server, SendGrid, Mailgun, Amazon SES, Postmark, etc.
  • Gmail / Microsoft 365 — OAuth 2.0 (XOAUTH2). Added by the integration_google and integration_microsoft365 integrations. Google and Microsoft have both disabled Basic Auth for SMTP/IMAP, so mailboxes on those providers must authenticate with a short-lived OAuth token — see OAuth mailboxes below.

IncomingMailServer records hold server, port, use_ssl, auth_type, username, password (and OAuth token fields when connected). A cron calls fetch_emails_from_all_servers(), which fetches unread mail from each server. For each message it:

  • skips auto-responders / out-of-office / bounces (loop guard),
  • threads replies onto the matching record when an In-Reply-To / References tracking id matches an existing Message,
  • otherwise routes the new mail through EmailRoute to create a record,
  • leaves a mail unread for manual handling if nothing matched.

Each message goes through IncomingMailServer._process_inbound_email(msg) (a standard email.message.Message), which returns True when the mail was taken in and False to leave it unread. A module that understands a particular kind of mail claims it by extending that method with __inherit__ = "IncomingMailServer": handle what is yours, return True, and call super() for everything else. The loop guard runs inside the base method, so an override sees machine-written mail before it is discarded — the Meetings app claims calendar answers this way (an iTIP METHOD:REPLY that Gmail or Outlook sends when an attendee presses Yes / No / Maybe; Exchange marks those X-Auto-Response-Suppress, which the guard treats as an auto-responder).

IncomingMailServer.inbound_address(company_id=None) returns the mailbox this install reads (the company’s own incoming server, else a shared one; None when there is none). Use it where an answer must come back to the app rather than to a person — a calendar invitation’s ORGANIZER, for one, since calendars send their replies there and ignore Reply-To.

The fetch cron ships in core:

- data_type: CronJob
identifier: cron_incoming_mail_fetch
name: Fetch Incoming Email
model: IncomingMailServer
method: fetch_emails_from_all_servers
frequency: 5
frequency_unit: Minutes
active: true

OutgoingMailServer records hold server, port, use_ssl, auth_type, username, password, and an optional company (empty for a server shared by every company). There is no per-user server. When sending, SMTP config is resolved with this priority:

  1. the mailbox the send names, if any (see Sending through a particular mailbox), then
  2. the acting company’s OutgoingMailServer, then
  3. a shared OutgoingMailServer (with company unset), then
  4. global config.yaml SMTP settings.

The relevant global keys:

KeyDefaultMeaning
SMTP_SERVER—SMTP host. If unset and no server record exists, sending raises a UserError.
SMTP_PORT587SMTP port.
SMTP_USERNAME—Login user.
SMTP_PASSWORD—Login password.
SMTP_USE_SSLTrueImplicit TLS on connect (port 465). False connects in plain and upgrades with STARTTLS when the server offers it (port 587); a server offering no encryption refuses the login.
SMTP_ALLOW_UNENCRYPTED_LOGINFalseSend the password even when the server offers no encryption at all. Only for a relay on a trusted network.
SMTP_FROM_EMAIL—The address mail is sent as. See “Which address mail is sent as” below.
SMTP_FROM_NAMEFullfinityDisplay name for mail with no author (password resets and similar). Authored mail uses the author’s name instead.
BASE_URL—Fallback public base URL, for a process that has never served a request. Normally leave it unset — see The install’s public URL.

Both server models expose test_connection() to validate credentials before saving.

Mail goes out as the identity the server is authenticated as — SMTP_FROM_EMAIL, or the connected mailbox of an OutgoingMailServer record — carrying the author’s name, with a Reply-To back to the author:

From: Admin <notifications@example.com>
Reply-To: admin@customer-domain.com

It is not sent as the author’s own address. A relay authenticated as notifications@example.com is not authorized to send for the author’s domain, so SPF fails there and DMARC cannot align — the relay rejects the message or the recipient’s provider files it as spam.

Two things opt out of the rewrite:

  • Leave SMTP_FROM_EMAIL unset (or use a server record with no login) and no sending identity is declared, so mail sends as the author’s address unchanged.
  • Set from_email on the Message and it is sent as exactly that, header and envelope both, untouched — this is how a campaign sends under its own address, whose SPF record the sending domain’s admin has set up. Pair it with from_name for the display name.

Message.from_email therefore means an explicit sender override on outbound mail; it is not set to the author’s address, which the author field already records. On inbound mail the same field holds the real external sender, which is often the only record of them — such a sender frequently has no contact record. Read from_display for a “From” column that resolves correctly in all three cases.

A Cloud workspace that has no outgoing server of its own still sends: through the platform’s sending service, as mail@<workspace host> under the company’s name. Two things differ from a mail server you configure:

  • an explicit from_email (a campaign’s own address) cannot be used as the sender there — it is set as the Reply-To instead, so replies still reach it;
  • a workspace has a daily sending allowance (smaller during a trial), and sending is paused for a workspace whose mail bounces or is reported as spam too often. A send beyond either fails with a message saying so, and stays in the queue to be resent.

Connecting a mailbox or adding an outgoing server takes over, exactly as on any other install. Self-hosted installs never use the built-in service.

Bounces and spam complaints reported by the service are recorded on the email that caused them, the same way a provider’s bounce webhook records them: bounced and bounce_reason for a permanent bounce, complained (“Reported as Spam”) for a complaint. Core only records a complaint; a module that keeps consent (a mailing list, say) reacts to complained changing in its update(). Both paths go through Message.record_delivery_problem(tracking_id, reason, complaint=False).

Mail to a Cloud workspace needs no mailbox either: anything sent to an address at the workspace’s host (support@acme.fullfinity.cloud) is received by the platform and handed to the workspace, where it is processed exactly as mail read from a connected mailbox — a reply threads onto the record it answers, a new email goes through the email routes, and a module that overrides IncomingMailServer._process_inbound_email to claim a kind of mail still claims it. IncomingMailServer.inbound_address() returns the built-in address (mail@<host>) when the workspace has no incoming server of its own.

By default a send goes through the acting company’s OutgoingMailServer, else a shared one (no company), else the server configuration’s SMTP_* settings. A message that must leave from one particular mailbox — a person writing from their own connected Gmail or Microsoft 365 inbox, so the email is from them and replies come back to them — names it:

server = await get_model("OutgoingMailServer").filter(oauth_email="founder@example.com").first()
await get_model("Message").queue_email(
author=None,
contact_emails=["writer@publication.example"],
subject="Your comparison of business systems",
body=html,
layout="Personal",
mail_server=server, # this mailbox, not the company's usual one
list_unsubscribe=unsubscribe_url, # per-recipient one-click unsubscribe
model="MyOutreach", document=outreach.id, # replies thread back onto this record
)

The message keeps it as mail_server (shown as Sent Through), so a retry goes out through the same mailbox. The sender identity follows that server exactly as above: an OAuth mailbox sends as its connected address.

How an email closes — don’t sign off in your template

Section titled “How an email closes — don’t sign off in your template”

An email closes with at most one sign-off, appended by the send: the sending user’s signature (their signature field), if they have one. Otherwise nothing is appended. A Custom Design email is never signed, because it carries its own footer.

The company name is never used as a sign-off. A branded email already names the company: in its header, and in the address line under the card when the header shows a logo instead of the name.

So an email template must not sign itself off. A template that closed with {{ company.name }} would print the company a second time under the header. Write the body and let it end — the closing is added for you. Naming the company inside a sentence (“your statement of account from {{ company.name }}”) is prose, not a sign-off, and is fine.

When the Portal app is installed and the message is anchored to a record whose model is published to the portal, the send appends a “View Online” button linking to that document — above the sign-off, in the recipient’s language. The link is a magic link: the customer opens the live document with no account and no login.

You get this for free. There is nothing to add to your email template and no per-model wiring:

  • A send raised from a form (an action returning {"type": "send_message", ...}) is anchored automatically, so quotes, invoices, orders, statements and tickets all carry the button.
  • A send raised in code needs model/document on queue_email / send_email (above).
  • Which models qualify is decided by the PortalAction records a module ships — the same data that puts a document type in the portal navigation. Publish a model to the portal and its mail gets links; don’t, and it doesn’t. See Portal.

Three deliberate exclusions:

  • An install that doesn’t know its public URL emits no button — a relative href is useless in an inbox, so nothing is appended rather than a dead link. See The install’s public URL below; it is auto-detected, so this normally resolves on its own.
  • A body that already contains a /portal/ link is left alone. If your template places the link itself, or the mail is a payment-link mail that carries its own portal URL, nothing is appended — the customer is never offered two destinations for one document.
  • A message with no customer to name gets no link (an unanchored password reset, an internal note, a record whose contact field is empty).

One token is issued per document and recipient, so resending a quote hands back the same URL rather than minting a new one, and each resend pushes its expiry out. Revoking a token (PortalAccess.revoke()) kills that customer’s link without touching anyone else’s.

Every link that leaves the app — the “View Online” button, open/click tracking, a campaign’s unsubscribe link, a booking link a user copies out of a form — is absolute, so the install has to know the URL the outside world reaches it on. It resolves in this order:

  1. The base_url setting, stored per database. It is auto-detected from the address an administrator is using when signed in, so an ordinary install needs no setup at all. It is learned only from an administrator’s request, and only when the address the browser reports matches the host the request arrived on (the proxy must pass the original Host header, as Caddy and a standard Nginx proxy_set_header Host $host do). No other request can change it: headers are written by whoever sends a request, and a public address set from them would let anyone send password-reset links to their own domain. Override it under Settings → General when auto-detection would get it wrong (a public domain that differs from the one staff use) and tick Lock Base URL so it stays as you set it.
  2. The BASE_URL config key, only as a fallback for a process that has never served a request — a worker that starts cold and flushes the mail queue before any request arrives. It lives in one file per server, so an install serving several databases cannot have one right answer there; prefer the setting.

Where neither is known, code that builds an outbound link emits nothing rather than a relative href that dies outside a browser tab already on the app.

In a template, {{ base_url }} is the same resolved value (see Rendering) — use it rather than reading config yourself.

send_immediately controls when delivery runs, never what is delivered. Both paths run the same delivery, so an immediate send gets the sign-off, the open-tracking pixel, click-wrapped links, and a send_state on the row exactly like a queued one — the only difference is that it runs inline instead of on the cron, and a delivery failure is raised to the caller rather than recorded on the row for retry.

Google and Microsoft have disabled Basic Auth (username + password) for SMTP and IMAP, so a Gmail or Microsoft 365 mailbox authenticates with a short-lived OAuth access token over the SASL XOAUTH2 mechanism instead. Two integrations add this capability; install the one you need from the Apps screen, then set it up from Settings → Email:

IntegrationProviderSMTP host / portIMAP host / port
integration_googleGmail / Google Workspacesmtp.gmail.com : 465 (SSL)imap.gmail.com : 993 (SSL)
integration_microsoft365Microsoft 365 / Outlooksmtp.office365.com : 587 (STARTTLS)outlook.office365.com : 993 (SSL)

One-time setup (admin):

  1. Register an OAuth app with the provider — a Google Cloud OAuth 2.0 Client, or an Azure AD app registration — authorizing the mail scopes (Gmail uses the restricted https://mail.google.com/ scope; Microsoft uses SMTP.Send + IMAP.AccessAsUser.All + offline_access). Set the redirect URI to <BASE_URL>/gmail_mail_auth or <BASE_URL>/microsoft_mail_auth respectively.
  2. Go to Settings → Email and open Google or Microsoft 365, then paste the Client ID / Client Secret (Microsoft also takes a Tenant — common, or a specific directory ID). These are install-wide: one app serves every mailbox, because the app identifies this deployment to the provider, not the mailbox.

Connecting a mailbox: the quickest route is Connect a Mailbox on the provider screen — it creates the outgoing and incoming servers with the provider’s SMTP/IMAP endpoints already filled in, and one consent authorizes both (the mail scope covers SMTP and IMAP alike, so there is no reason to ask twice). To connect an existing server instead, set its auth_type to Gmail or Microsoft 365, save, then click Connect.

Either way the callback stores the refresh token on the record and fills in the connected mailbox address; the framework refreshes the access token automatically on every send/fetch. The envelope sender is forced to the connected mailbox (Gmail/Microsoft reject a mismatched From).

Connect as many mailboxes as you need — each is its own pair of server records holding its own tokens, all authorized against the same app. Which one a given message uses is resolved most specific first: the mailbox the send names → the acting company’s server → a shared server → the SMTP_* settings.

Adding another OAuth provider. The transport is generic: core’s mail models declare an auth_type Selection and an overridable async def _resolve_access_token(self) hook that returns a valid access token. A provider module contributes its label via _selection_add = {"auth_type": ["<Label>"]} on an __inherit__ of both mail-server models, overrides _resolve_access_token to handle its own auth_type (calling super() for the rest), and adds a connect action plus an OAuth callback route. integration_google is the reference implementation.