Explore Salesforce SingleEmailMessage Class Methods

May 19, 2023

 

By using SingleEmailMessage we can send emails. SingleEmailMessage is a class which has some important methods to send email.

 

SingleEmailMessage contains the methods below.

 

setTargetObjectId(targetObjectId)

Required if using a template, optional otherwise. pass the ID of the contact, lead, or user to which the email will be sent.

If you set the contact Id and send email, the activity history record will be created on the contact record.

This method only accepts contact, lead, or user Id.

Signature

public Void setTargetObjectId(ID targetObjectId)

Parameters

targetObjectId

Type: ID

Return Value

Type: Void

Usage

Do not specify the IDs of records that have the Email Opt Out option selected.

All emails must have a recipient value in at least one of the following fields:

 

setTreatTargetObjectAsRecipient(treatAsRecipient)

Optional. If set to true, the targetObjectId (a contact, lead, or user) is the recipient of the email. If set to false, the targetObjectId is supplied as the WhoId field for template rendering but isn’t a recipient of the email. The default is true.

Parameters

treatAsRecipient

Type: Boolean

Return Value

Type: void

Usage

Note

You can set TO, CC, and BCC addresses using the email messaging methods regardless of whether a template is used for the email or the target object is a recipient.

 

setWhatId(whatId)

If you specify a contact for the targetObjectId field, you can specify an optional whatId as well. This helps to further ensure that merge fields in the template contain the correct data.

This is an optional method.

If you want to create activity history on the custom object record page then this method will be used.

You can pass Id of the custom object to which the email will be sent.

Signature

public Void setWhatId(ID whatId)

Parameters

whatId

Type: ID

Return Value

Type: Void

Usage

The value must be one of the following types:

 

setToAddresses(toAddresses)

Optional. A list of email addresses or object IDs of the contacts, leads, and users you’re sending the email to. The maximum size for this field is 4,000 bytes. The maximum total of toAddressesccAddresses, and bccAddresses per email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API.

Signature

public Void setToAddresses(String[] toAddresses)

Parameters

toAddresses

Type: String[]

Return Value

Type: void

Usage

All emails must have a recipient value in at least one of the following fields:

 

setBccAddresses(bccAddresses)

Optional. A list of blind carbon copy (BCC) addresses or object IDs of the contacts, leads, and users you’re sending the email to. The maximum size for this field is 4,000 bytes. The maximum total of toAddressesccAddresses, and bccAddresses per email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API.

Signature

public Void setBccAddresses(String[] bccAddresses)

Parameters

bccAddresses

Type: String[]

Return Value

Type: void

Usage

All emails must have a recipient value in at least one of the following fields:

 

setEntityAttachments(ids)

Optional, This method takes an Array of Ids of Document, ContentVersion, or Attachment items to attach to the email.

Signature

public void setEntityAttachments(List<String> ids)

Parameters

ids

Type: List<String>

Return Value

Type: void

 

setFileAttachments(fileNames)

This is an optional method. You can pass the list of file names of the binary and the text files you want to attach in the email.

Signature

public void setFileAttachments(EmailFileAttachment[] fileNames)

Parameters

fileNames

Type: Messaging.EmailFileAttachment[]

Return Value

Type: void

Usage

You can attach multiple files as long as the total size of all attachments does not exceed 10 MB.

 

setHtmlBody(htmlBody)

Optional. The HTML version of the email, specified by the sender. The value is encoded according to the specification associated with the organization. Specify a value for setTemplateIdsetHtmlBody, or setPlainTextBody. Or, you can define both setHtmlBody and setPlainTextBody.

Signature

public Void setHtmlBody(String htmlBody)

Parameters

htmlBody

Type: String

Return Value

Type: void

 

setPlainTextBody(plainTextBody)

Optional. The text version of the email, specified by the sender. Specify a value for setTemplateIdsetHtmlBody, or setPlainTextBody. Or, you can define both setHtmlBody and setPlainTextBody.

Signature

public Void setPlainTextBody(String plainTextBody)

Parameters

plainTextBody

Type: String

Return Value

Type: void

 

setOrgWideEmailAddressId(emailAddressId)

Optional, organization-wide email address ID associated with the outgoing email. If you’re using Apex to send emails from the guest user, set the sender to the verified org-wide email address or the emails are blocked. In the email display name can be set in the organization-wide record which you created in salesforce.

The object's DisplayName field cannot be set if the setSenderDisplayName field is already set.

Signature

public Void setOrgWideEmailAddressId(ID emailAddressId)

Parameters

emailAddressId

 Type: ID

Usage 

After you create an org-wide email address, you’re sent a confirmation email to verify it. Copy the Id from the URL and use the setOrgWideEmailAddressId(Id) method on your instance of Messaging.SingleEmailMessage.

OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address ='doNotReply@<somedomain>.com'];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
if ( owea.size() > 0 ) {
    mail.setOrgWideEmailAddressId(owea.get(0).Id);
}
 
 

setOptOutPolicy(emailOptOutPolicy)

 
Optional. If you added recipients by ID instead of email address and the Email Opt Out option is set, this method determines the behavior of the sendEmail() call. If you add recipients by their email addresses, the opt-out settings for those recipients aren’t checked and those recipients always receive the email.
 
Parameters
 
Possible values of the emailOptOutPolicy parameter are:
SEND (default)—The email is sent to all recipients. The recipients’ Email Opt Out setting is ignored. The setting Enforce
email privacy settings is ignored.
FILTER—No email is sent to recipients that have the Email Opt Out option set. Emails are sent to the other recipients.
The setting Enforce email privacy settings is ignored.
REJECT—If any of the recipients have the Email Opt Out option set, sendEmail() throws an error and no email is
sent. The setting Enforce email privacy settings is respected, as are the selections in the data privacy record based on the Individual
object. If any of the recipients have Don’t Market, Don’t Process, or Forget this Individual selected, sendEmail() throws an
error and no email is sent.
 

Example

This example shows how to send an email with the opt-out setting enforced. Recipients are specified by their IDs. The FILTER option causes the email to be sent only to recipients that haven’t opted out from email. This example uses dot notation of the email properties, which is equivalent to using the set methods.

 

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
// Set recipients to two contact IDs.
// Replace IDs with valid record IDs in your org.
message.toAddresses = new String[] { '003D000000QDexS', '003D000000QDfW5' };
message.optOutPolicy = 'FILTER';
message.subject = 'Opt Out Test Message';
message.plainTextBody = 'This is the message body.';
Messaging.SingleEmailMessage[] messages =
new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
if (results[0].success) {
    System.debug('The email was sent successfully.');
} else {
   System.debug('The email failed to send: '+ results[0].errors[0].message);
}

 

setReferences(references)

Optional. The References field of the outgoing email. Identifies an email thread. Contains the parent emails' References and message IDs, and possibly the In-Reply-To fields.

Signature

public Void setReferences(String references)

Parameters

references

 Type: String
Return Value

Type: void

 
Send Email Message Using Apex Code like this:
 
 
 
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
string[] to = new string[] {toAddress};
message.setToAddresses(to);
string[] ccAddr = new string[] {'ccAddress'};
message.setCcAddresses(ccAddr);
OrgWideEmailAddress orgWideEmailAddress = [SELECT Id, Address, DisplayName FROM OrgWideEmailAddress Limit 1];
message.setOrgWideEmailAddressId(orgWideEmailAddress.Id);
message.setTreatTargetObjectAsRecipient(false);
message.setTargetObjectId(conId);
message.setSubject('subject');
message.setSaveAsActivity(true);
message.setEntityAttachments(contentVersionIds);
message.setHtmlBody('This is html body');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email1 });
 
 
 

I hope this blog helped you!