apex-outbound-email-patterns
Apex outbound email via Messaging.SingleEmailMessage — OrgWideEmailAddress, ReplyTo and Reply-To header semantics, EmailTemplate merging with whatId/targetObjectId, attachment patterns, daily governor limits, and the difference between transactional sends and Email Alerts. NOT for inbound email handling (use apex/inbound-email-handler) or Marketing Cloud sends (use integration/marketing-cloud-rest-api).
Best use case
apex-outbound-email-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Apex outbound email via Messaging.SingleEmailMessage — OrgWideEmailAddress, ReplyTo and Reply-To header semantics, EmailTemplate merging with whatId/targetObjectId, attachment patterns, daily governor limits, and the difference between transactional sends and Email Alerts. NOT for inbound email handling (use apex/inbound-email-handler) or Marketing Cloud sends (use integration/marketing-cloud-rest-api).
Teams using apex-outbound-email-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/apex-outbound-email-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How apex-outbound-email-patterns Compares
| Feature / Agent | apex-outbound-email-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Apex outbound email via Messaging.SingleEmailMessage — OrgWideEmailAddress, ReplyTo and Reply-To header semantics, EmailTemplate merging with whatId/targetObjectId, attachment patterns, daily governor limits, and the difference between transactional sends and Email Alerts. NOT for inbound email handling (use apex/inbound-email-handler) or Marketing Cloud sends (use integration/marketing-cloud-rest-api).
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Marketing
Discover AI agents for marketing workflows, from SEO and content production to campaign research, outreach, and analytics.
Best AI Agents for Marketing
A curated list of the best AI agents and skills for marketing teams focused on SEO, content systems, outreach, and campaign execution.
AI Agent for Cold Email Generation
Discover AI agent skills for cold email generation, outreach copy, lead personalization, CRM support, and sales-adjacent messaging workflows.
SKILL.md Source
# Apex Outbound Email Patterns Outbound email from Apex looks simple — instantiate `Messaging.SingleEmailMessage`, populate fields, call `Messaging.sendEmail`. The patterns that turn it into a reliable production integration are not in the SOAP API guide: they live in the interaction between `OrgWideEmailAddress`, the `whatId`/`targetObjectId` merge contract, the daily governor cap of 5,000 external emails, and the differences between SingleEmailMessage and Email Alerts triggered from Flow. The recurring questions are: how do we send "from a shared support@" address rather than the running user; how do we make replies go to a routing address rather than the From; how do we merge an EmailTemplate against an Account when the template is keyed to a Contact; and why does `setHtmlBody` ignore merge fields. These have specific answers — most of them involve `setOrgWideEmailAddressId`, `setReplyTo`, or `renderStoredEmailTemplate`. Two governor facts shape every design decision. First, the org's daily external-email limit is 5,000 and counts every recipient on every send (a 4-recipient send burns 4 from the bucket). Second, sending email is treated as a non-transactional side effect — if your transaction rolls back, the email still goes out. That last part traps every team at least once. ## Recommended Workflow 1. **Decide the send mechanism first.** If the trigger is admin- configurable (a record meeting criteria), use a Flow Email Alert — admins can edit the template, the recipient logic, and the from-address without a deployment. Reach for `Messaging.SingleEmailMessage` only when you need conditional content, attachments computed at runtime, or programmatic recipient selection. 2. **Configure the OrgWideEmailAddress before writing Apex.** Setup → Email → Organization-Wide Addresses, verify the address, note its Id (or query `SELECT Id FROM OrgWideEmailAddress WHERE Address='support@acme.com'`). Without this, every send shows the running user as From. 3. **Build the message with `setOrgWideEmailAddressId` first, then `setReplyTo`.** The OWE controls the visible From; the ReplyTo controls where replies land. They are distinct concerns and are commonly confused. 4. **For template-merged sends, use `renderStoredEmailTemplate` when the merge target is not a Contact/Lead/User.** The built-in `setTemplateId` + `setTargetObjectId` path requires a Contact, Lead, or User. Anything else (Account, Case, custom object) needs the explicit render call with a `whatId`. 5. **Always set `setSaveAsActivity(true)` for record-related sends.** This writes an EmailMessage record to the related-to object's activity timeline — invaluable for support audits. 6. **Handle the `Messaging.SendEmailResult[]` return value.** It is a list parallel to the input — each element carries `isSuccess()`, `getErrors()`, and a status code. Treating the call as fire-and- forget hides per-recipient failures. 7. **Cap and observe daily-limit errors.** Catch `System.HandledException` containing `SINGLE_EMAIL_LIMIT_EXCEEDED` and degrade gracefully (queue for retry the next day, surface to monitoring). 5,000/day is per-org, not per-user. ## SingleEmailMessage vs Email Alert vs MassEmailMessage - **SingleEmailMessage**: programmatic; up to 100 recipients per call; supports attachments, OWE, ReplyTo, custom merge. - **Email Alert (Flow)**: declarative; admin-editable template and recipient set; respects OWE; cannot conditionally branch attachments. - **MassEmailMessage**: deprecated for new work; keep only legacy references; use SingleEmailMessage in a loop with proper bulkification. ## What This Skill Does Not Cover | Topic | See instead | |---|---| | Inbound email handling | `apex/inbound-email-handler` | | Marketing Cloud sends from Salesforce | `integration/marketing-cloud-rest-api` | | Email-to-Case routing rules | `admin/email-to-case-config` | | Email Deliverability settings (Setup → Email) | `admin/email-deliverability` |
Related Skills
mfa-enforcement-patterns
Design MFA enforcement: auto-enablement, Salesforce Authenticator rollout, exceptions, service accounts, API-only users, SSO interop, and audit. Trigger keywords: MFA, multi-factor, two-factor, Salesforce Authenticator, MFA exception, MFA SSO, api-only MFA. Does NOT cover: end-user password policies, device-trust posture, or non-Salesforce IdP configuration.
encrypted-field-query-patterns
Design SOQL, filters, reporting, and indexes against Shield Platform Encryption fields. Trigger keywords: Shield Platform Encryption, encrypted field query, probabilistic vs deterministic encryption, encrypted SOQL filter, encrypted field index. Does NOT cover: Classic Encryption (deprecated), field-level security policy, or tenant secret key rotation.
apex-managed-sharing-patterns
Grant row-level access programmatically via __Share records when declarative sharing rules cannot express the policy. NOT for OWD, role hierarchy, or criteria-based sharing rule design.
omnistudio-testing-patterns
Use when testing or validating OmniStudio components — OmniScript preview, Integration Procedure step debugging, DataRaptor field-mapping validation, and end-to-end UTAM-based automation. NOT for Apex unit testing or standard Flow debugging.
omnistudio-error-handling-patterns
Use when designing fault behavior across Integration Procedures, DataRaptors, OmniScripts, and FlexCards — error routing, user-facing messaging, retry semantics, and idempotency. Triggers: 'omnistudio error', 'integration procedure fault', 'dataraptor error handling', 'omniscript retry', 'flexcard action failure'. NOT for general Apex exception design or Flow fault paths.
omnistudio-ci-cd-patterns
Use when designing or implementing CI/CD pipelines for OmniStudio components — DataPack export/import, versioning, environment promotion, and automated deployment. NOT for standard Salesforce metadata CI/CD or Apex-only pipelines.
omniscript-design-patterns
Use when designing or reviewing OmniScripts for guided experiences, step structure, branching, save/resume, and the boundary between OmniScript, Integration Procedures, DataRaptors, and custom LWCs. Triggers: 'omniscript design', 'too many steps in omniscript', 'save and resume omniscript', 'branching in omniscript', 'when should this be an integration procedure'. NOT for deep Integration Procedure or DataRaptor design when the guided interaction layer is not the main concern.
integration-procedure-cacheable-patterns
Use when designing Integration Procedures (IPs) with platform cache to cut latency and callout load. Covers cache key design, TTL selection, per-user vs org-wide partitions, invalidation on data changes, and safe fallback on cache miss/stale. Does NOT cover general IP authoring (see omnistudio-error-handling-patterns) or LWC client-side caching.
flexcard-design-patterns
Use when designing, building, or reviewing OmniStudio FlexCards — including data source selection, card states, actions, conditional visibility, flyout configuration, and child card iteration. Triggers: 'FlexCard', 'card template', 'flyout', 'card action', 'card state', 'data source', 'child card', 'conditional visibility'. NOT for OmniScript design, standalone LWC development, or Apex controller architecture outside the FlexCard context.
dataraptor-patterns
Use when designing or reviewing OmniStudio DataRaptors, especially Extract versus Turbo Extract versus Transform versus Load, field mapping strategy, performance tradeoffs, and when to move work into Integration Procedures or Apex. Triggers: 'DataRaptor Extract', 'Turbo Extract', 'DataRaptor Load', 'DataRaptor Transform', 'OmniStudio data mapping'. NOT for overall OmniScript journey design or Integration Procedure sequencing when the main question is not the DataRaptor shape itself.
wire-service-patterns
Use when designing or reviewing Lightning Web Components that use `@wire`, Lightning Data Service, UI API, or the GraphQL wire adapter, especially for reactive parameters, cache behavior, and refresh strategy. Triggers: 'wire service', 'refreshApex', 'reactive parameter', 'getRecord', 'wire vs imperative Apex'. NOT for component communication or generic lifecycle issues when data provisioning is not the main concern.
message-channel-patterns
Use when implementing Lightning Message Service (LMS) to enable cross-DOM communication between LWC, Aura, and Visualforce components on the same Lightning page, using message channels. Triggers: 'communicate between unrelated LWC components', 'send data between Visualforce and LWC', 'lightning message service not working', 'APPLICATION_SCOPE vs default scope', 'message channel metadata deployment'. NOT for parent-child component communication (use component-communication) or server-side events.