Skip to main content

Inbound email handlers in Apex: treat every message as hostile input

An Apex email service is a public endpoint with an unusual transport. Anyone who knows the address can send it a message, and the platform hands that message to your Messaging.InboundEmailHandler class, which then runs as a Salesforce user and writes records. The From line, the subject, the body and every attachment are chosen by the sender.

Email handlers tend to get less review than REST endpoints because they look like plumbing: create a case from a reply, log an approval, attach a document. This post covers where handlers go wrong, the email service settings that matter, and a pattern for acting on email without trusting who it claims to be from.

What the handler receives

The Apex email service calls handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope). Almost everything in both objects is attacker-controlled:

Field Controlled by Safe to use as
email.fromAddress, email.fromName Sender A hint for matching, never an identity
email.replyTo Sender, never verified Nothing security-related
envelope.fromAddress Sender's mail server A hint
email.subject, plainTextBody, htmlBody Sender Untrusted text
email.headers Sender, plus relaying servers Audit evidence
binaryAttachments, textAttachments Sender, including file name and type Untrusted files

Mistake 1: the sender address as identity

The most common handler bug looks up a user by the From address and acts on their behalf:

global class ExpenseApprovalHandler implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(
            Messaging.InboundEmail email, Messaging.InboundEnvelope env) {
        User approver = [SELECT Id FROM User WHERE Email = :email.fromAddress LIMIT 1];
        Expense__c exp = [SELECT Id, Status__c FROM Expense__c
                          WHERE Name = :email.subject.trim() LIMIT 1];
        if (email.plainTextBody.trim().startsWithIgnoreCase('APPROVE')) {
            exp.Status__c = 'Approved';
            exp.Approved_By__c = approver.Id;
            update exp;
        }
        return new Messaging.InboundEmailResult();
    }
}

Anyone who knows a manager's address and an expense number can approve it. Sender authentication helps less than people expect: SPF and DKIM tell you a server was allowed to send for a domain, not that a particular person wrote the message, and the Reply-To header is never checked at all. That is CWE-290, authentication bypass by spoofing.

A pattern that does not trust the From line

Put the proof in the message you sent, not in the message you receive. When the app emails an approver, include a random, single-use token tied to that record and that user, and require it in the reply:

global with sharing class ExpenseApprovalHandler implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(
            Messaging.InboundEmail email, Messaging.InboundEnvelope env) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        Matcher m = Pattern.compile('\\[ref:([A-Za-z0-9]{40,64})\\]')
                           .matcher(email.subject == null ? '' : email.subject);
        if (!m.find()) {
            result.success = false;
            result.message = 'This address only accepts replies to approval requests.';
            return result;
        }
        List<Approval_Token__c> tokens = [
            SELECT Id, Expense__c, Approver__c, Approver__r.Email, Used__c, Expires__c
            FROM Approval_Token__c
            WHERE Token__c = :m.group(1) AND Used__c = false AND Expires__c > :System.now()
            LIMIT 1
        ];
        if (tokens.isEmpty()
                || !tokens[0].Approver__r.Email.equalsIgnoreCase(email.fromAddress)) {
            result.success = false;
            result.message = 'This approval link is no longer valid.';
            return result;
        }
        ApprovalService.decide(tokens[0], email.plainTextBody);
        return result;
    }
}

The token is the authenticator, generated with Crypto.generateAesKey(256) and hex-encoded when the request is sent, marked used after one decision and expired after a few days. The From check is kept as a second signal. ApprovalService.decide reads only the first word of the body and ignores everything else. For anything with real consequences, such as payments, access grants or contract changes, prefer a reply that sends the user back to a signed-in page to confirm.

The email service settings that matter

Setup gives you four controls on the email service and its addresses:

  • Accept Email From. An allowlist of addresses or domains, on the service and on each address. When both are set, a sender must appear in both. Left blank, the service accepts mail from anyone. Use it whenever the senders are a known set, such as one partner domain or your own staff.
  • Authenticate Senders. Checks the sending server's authentication before the message reaches your class, with an Unauthenticated Sender Action for messages that fail. Turn it on. It raises the cost of spoofing a domain even though it does not prove a person.
  • Context User. The address's context user is the user the service runs as, and the service assumes that user's permissions. Use a dedicated user with access to the objects this handler writes and nothing more, never an admin.
  • Accept Attachments. Choose the narrowest option the feature needs. A handler that only reads replies should not accept binary attachments.

In metadata, the same settings appear as authorizedSenders and isAuthenticationRequired on EmailServicesFunction, with isTlsRequired for the transport, and runAsUser and authorizedSenders on each EmailServicesAddress. Deploy them from source so a changed setting shows up in review.

Mistake 2: storing the body as markup

htmlBody is attacker HTML. If the handler copies it into a rich text field, a Visualforce page with escape="false" or an outbound notification, the sender has a stored cross-site scripting or HTML injection channel into your users' screens. Store plainTextBody where possible. When HTML must be kept, sanitise it, and never place it in an outbound setHtmlBody without String.escapeHtml4.

Mistake 3: trusting attachments

The file name, the MIME type and the content are all chosen by the sender. Do not use the file name in a path or a query, do not decide what a file is from its declared type, cap the size you store, and save attachments as files that are shared only with the record they belong to. Do not assume anything scanned them for malware before your class ran.

Email-to-Case is the same surface

Email-to-Case turns every sender on the internet into a writer of Case Subject, Description and the EmailMessage body. That was always an XSS and data quality concern. With Agentforce reading case text, it is also a prompt-injection channel: see Web-to-Lead and Web-to-Case as prompt-injection channels.

A review checklist

  1. Every handler class: what does it write, and what in the message decides that?
  2. No identity from fromAddress, replyTo or headers alone.
  3. Accept Email From set wherever senders are known, Authenticate Senders on.
  4. A dedicated, minimal context user per address.
  5. plainTextBody stored, htmlBody sanitised or dropped.
  6. Attachments limited by type and size and shared narrowly.
  7. Handler and service settings in version control.

Where Vulkro for Salesforce fits

vulkro-sf scan reads handler classes together with their EmailServicesFunction metadata. email-handler-trusts-sender-address flags a handler that uses the sender address as the caller's identity and then writes records, email-handler-trusts-reply-to does the same for Reply-To and sender headers, and email-service-accepts-unauthenticated-mail flags an active service with authentication off and no authorized senders, noting when TLS is not required. apex-email-html-injection covers inbound message fields placed in an outbound HTML body, and sf-forcedleak-email-to-case covers case text that reaches an agent. On a live org, vulkro-sf org mail -t prod lists email service addresses bound to non-Salesforce domains (SF-MAIL-002).

FAQ

Does "Authenticate Senders" stop spoofed email?

It rejects or flags mail whose sending server fails authentication for the claimed domain. It does not prove which person sent a message, and it does not cover the Reply-To header. Never treat it as user authentication.

Which user does an Apex email handler run as?

The context user configured on the email service address. The service assumes that user's permissions, so give it a dedicated, minimal user.

Can I let users approve records by email?

Yes, if the approval depends on a single-use, expiring token you sent them, not on their address. For high-impact actions, link back to a signed-in confirmation page.

See the org mail command and Vulkro for Salesforce, or start a 14-day trial. Related: EmailMessage visibility in Salesforce and Visualforce XSS and escape="false".