When sending an email using a template in Apex, the “targetObjectId” is typically required, which must be the ID of a Lead, Contact, or User. However, in many cases, you may not have a targetObjectId available, especially when sending an email from a custom object to an external email address that isn’t associated with a Lead, Contact, or User in Salesforce.
Many articles suggest creating a dummy Contact record to use as the targetObjectId, but this workaround can be cumbersome and unreliable.
Here’s a more effective solution that avoids the need for a dummy Contact or setting targetObjectId. See the sample code below.
//The ID of the Salesforce record whose values are used as merge fields in the email template.
String recordId = 'sf_record_id';
//The ID of Salesforce email template
String EmailTemplateId = '00X8b00000avbabc';
//create a list to store the email message records
list<Messaging.SingleEmailMessage> EmailMessageList = new list<Messaging.SingleEmailMessage>();
// Create the email message
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Set to address
email.setToAddresses(new String[] { '[email protected]' });
//Renders a text, custom, HTML, or Visualforce email template that exists in the database into an instance of Messaging.SingleEmailMessage
Messaging.SingleEmailMessage renderResult = Messaging.renderStoredEmailTemplate(
EmailTemplateId,
NULL,
recordId
);
// Set the email subject
email.setSubject(renderResult.getSubject());
// Set the email body
if(renderResult.getHtmlBody() == NULL)
email.setPlainTextBody(renderResult.getPlainTextBody());
else
email.setHtmlBody(renderResult.getHtmlBody());
email.setSaveAsActivity(false);
// Specify OrgWideEmailAddress for sender type
email.setOrgWideEmailAddressId([SELECT Id FROM OrgWideEmailAddress WHERE Address = '[email protected]' LIMIT 1].Id);
//add SingleEmailMessage instance into list
EmailMessageList.add(email);
//send email
Messaging.sendEmail(EmailMessageList);