Tuesday, August 30, 2022

Sending Email in Salesforce using Apex

This is a common snippet to send an email using Salesforce Apex:

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new List<String>{'demo@sf.com'});

email.setPlainTextBody('Sample body');
email.setSubject('Sample subject');

List<Messaging.SendEmailResult> results = Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{ email });

for (Messaging.SendEmailResult sr : results) {
    if (!sr.isSuccess()) {
        List<Messaging.SendEmailError> errors = sr.getErrors();
        String errorString = String.join(errors, ', ');
        throw new AuraHandledException(errorString);
    }
}

Sending files with Email

Now assume that we have an order record in Salesforce, and multiple files have been uploaded in Files related list. And we would like to mail a recipient attaching all these files. There is a method setEntityAttachments() on SingleEmailMessage class which accepts an array of ContentVersion Ids.

Make sure that you pass the ContentVersion Ids as a list of String 😐

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

Save Email as an activity

What if you would like to mail to a recipient but at the same time save the email record as an activity? For this, use setSaveAsActivity() and setWhatId() methods as below:

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
...
...
...
email.setEntityAttachments(new List<String>(contentVersionIds));
email.setSaveAsActivity(true);
email.setWhatId(orderId);

Replace Merge fields in Email Template

Now assume that you have already defined an email template, and there are merge fields (placeholders) both in the body and subject of the email template. When you send the email, these merge fields should get replaced with the Salesforce data from the record. Use renderStoredEmailTemplate() of Messaging class as below:

EmailTemplate emailTemplate = [SELECT Id, Body, Subject FROM EmailTemplate WHERE DeveloperName = :emailTemplateName LIMIT 1];

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

email.setPlainTextBody(Messaging.renderStoredEmailTemplate(emailTemplate.Id, UserInfo.getUserId(), recordId).plainTextBody);
email.setSubject(Messaging.renderStoredEmailTemplate(emailTemplate.Id, UserInfo.getUserId(), recordId).getSubject());

Remember that executing the renderStoredEmailTemplate() counts toward the SOQL governor limit as one query. This is described more in detail here.

There is a lot of information provided in Salesforce documentation, so do refer the Messaging and SingleEmailMessage classes.

And finally, a full fledged example of sending email using Salesforce Apex: https://gist.github.com/iamsonal/3ccd44b319724f4d03cdb4df0bde54d0

Share This:    Facebook Twitter

0 comments:

Post a Comment

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top