What Classes the Messaging Namespace Provide for Programmatic Email in Salesforce

According to the Salesforce Apex outbound email documentation, the Messaging namespace provides several key classes. Messaging.SingleEmailMessage sends individual emails with full customization—HTML/text body, attachments, CC/BCC, and custom headers. Messaging.MassEmailMessage sends emails to multiple recipients using email templates, limited to 250 recipients per call. Messaging.sendEmail() executes email sends by accepting an array of email messages and returning results. Messaging.SendEmailResult contains the success/failure status and error details for each email. Messaging.InboundEmail represents inbound emails for Email Services processing.

Which Properties SingleEmailMessage Exposes for Controlling Email Content and Behavior

Key properties include: setToAddresses(), setCcAddresses(), setBccAddresses(), setSubject(), setHtmlBody(), setPlainTextBody(), setTemplateId(), setTargetObjectId(), setWhatId(), setFileAttachments(), and setSaveAsActivity().

How to Send a Basic Email Using Apex SingleEmailMessage


Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

email.setToAddresses(new String[] {'recipient@example.com'});
email.setSubject('Your Subject Line');

email.setHtmlBody("<html><body><h1>Hello</h1><p>Email content.</p></body></html>");
email.setPlainTextBody('Hello - Email content here.');

email.setSaveAsActivity(true);

Messaging.SendEmailResult[] results =
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });

How to Send Template-Based Emails with Merge Fields Using Apex


Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

email.setTemplateId('00X000000000001'); // Template ID
email.setTargetObjectId(contactId);    // Contact for merge fields
email.setWhatId(opportunityId);        // Related Opportunity
email.setSaveAsActivity(true);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });

What Governor Limits Constrain Apex Email Sending in Salesforce

Apex email is subject to governor limits:

  • 5,000 single emails per day (org-wide, varies by edition)
  • 10 sendEmail() invocations per Apex transaction
  • 100 recipients per SingleEmailMessage call
  • 250 recipients per MassEmailMessage call

How to Properly Handle Email Send Results and Errors in Apex


Messaging.SendEmailResult[] results = Messaging.sendEmail(emails);

for (Messaging.SendEmailResult result : results) {

    if (!result.isSuccess()) {

        for (Messaging.SendEmailError error : result.getErrors()) {
            System.debug('Error: ' + error.getMessage());
        }
    }
}

How to Send Automated Emails from Apex Triggers Based on Record Events


trigger SendWelcomeEmail on Contact (after insert) {

    List emails =
        new List();

    for (Contact c : Trigger.new) {

        if (c.Email != null) {

            Messaging.SingleEmailMessage email =
                new Messaging.SingleEmailMessage();

            email.setTargetObjectId(c.Id);
            email.setTemplateId(welcomeTemplateId);

            emails.add(email);
        }
    }

    if (!emails.isEmpty()) {
        Messaging.sendEmail(emails);
    }
}

How to Use Batch Apex for Large-Scale Email Sending Within Governor Limits


global class EmailBatch implements Database.Batchable {

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(
            [SELECT Id, Email FROM Contact WHERE Email != null]
        );
    }

    global void execute(Database.BatchableContext bc,
                        List scope) {

        List emails =
            new List();

        for (Contact c : scope) {

            Messaging.SingleEmailMessage email =
                new Messaging.SingleEmailMessage();

            email.setTargetObjectId(c.Id);
            email.setSubject('Batch Email');
            email.setPlainTextBody('Hello from Batch Apex');

            emails.add(email);
        }

        if (!emails.isEmpty()) {
            Messaging.sendEmail(emails);
        }
    }

    global void finish(Database.BatchableContext bc) { }
}

How to Attach Files to Emails Sent Through Apex Code


Messaging.EmailFileAttachment attachment =
    new Messaging.EmailFileAttachment();

attachment.setFileName('document.pdf');
attachment.setBody(pdfBlob);
attachment.setContentType('application/pdf');

email.setFileAttachments(
    new Messaging.EmailFileAttachment[] { attachment }
);

Apex Email Best Practices for Reliable and Scalable Sending

Follow these practices for reliable email sending.Bulkify:Collect emails in a list and send with a single sendEmail() call to minimize limit consumption.Check Limits:Use Limits.getEmailInvocations() to check remaining capacity before sending.Handle Errors:Always check SendEmailResult and handle failures gracefully.Respect Opt-Out:Checkopt-outandunsubscribeflags before sending.Log Activity:Set saveAsActivity(true) foremail tracking.Test Thoroughly:Use @isTest with Messaging.sendEmail() assertions.

What Limitations Make Native Apex Email Insufficient for Large-Scale Operations

Understand what Apex email cannot do.Strict Limits:5,000 daily limit constrainsemail campaignsat scale.Limited Tracking:Native Apex doesn’t provideopen ratesor click tracking without additional development.Deliverability:Shared Salesforce IPs may affectemail deliverability. No dedicated IP option natively.No Scheduling:Scheduling requires custom development with Scheduled Apex.Template Constraints:MassEmailMessage requires templates, and dynamic content options are limited.

How Apex Email Integrates with Marketing Workflows and Automation

Apex email integrates with marketing workflows in several ways.Campaign Integration:Link sent emails toemail campaignsfor attribution tracking.Automation:Buildemail automationwith scheduled Apex fordrip campaigns.Sequences:Implementemail sequencesandfollow-up sequenceswith custom Apex logic.

Enhanced Email Capabilities That Extend Beyond Apex Governor Limits

For organizations needing enhanced email beyond Apex limits,MassMaileroperates 100% native to Salesforce. Unlimited sending without governor limits. Completeemail capabilitieswithemail analytics. Use theemail builderto create engaging templates withcontact listtargeting.

Key Takeaways

  • The Apex Messaging namespace provides SingleEmailMessage and MassEmailMessage for programmatic sending
  • Governor limits constrain Apex email to 5,000 daily sends and 10 calls per transaction
  • Use Batch Apex for large-scale sends while respecting limits
  • Native solutions extend capabilities beyond Apex limitations

Need to send email at scale without wrestling with Apex governor limits?Schedule a walkthrough with our teamto see how MassMailer delivers 100% native Salesforce email with unlimited sending, dedicated IPs for optimaldeliverability, and built-inanalytics—all without writing a single line of Apex. Explorebest-in-class capabilitiestoday →