SingleEmailMessage Class
Contains methods for sending single email messages.
Sending an email by using Apex requires domain-level and user-level email verification. System-generated emails also require verification of the From email address. Email delivery fails if any of these verifications is incomplete. See Requirements to Send Email from Salesforce.
SingleEmailMessage extends Email and inherits all of its methods. All base email (Email class) methods are also available to the SingleEmailMessage objects. Emails sent via SingleEmailMessage count against the sending organization’s daily single email limit.
Email properties are readable and writable. Each property has corresponding setter and getter methods. For example, the toAddresses() property is equivalent to the setToAddresses() and getToAddresses() methods. Only the setter methods are documented. However, the getTemplateName() method doesn’t have an equivalent setter method; use setTemplateId() to specify a template name.
See Also
The following are constructors for SingleEmailMessage.
-
Creates a new instance of the
Messaging.SingleEmailMessageclass.
Creates a new instance of the Messaging.SingleEmailMessage class.
public SingleEmailMessage()
The following are methods for SingleEmailMessage. All are instance methods. All base email (Email class) methods are also available to the SingleEmailMessage objects. These methods are described in Email Class (Base Email Methods).
-
Returns the map of custom headers previously set for the email. Returns null if no custom headers were set.
-
Optional. Returns a boolean value based on the value set by the
setOneClickPostmethod. Default isfalse. -
The name of the template used to create the email.
-
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
toAddresses,ccAddresses, andbccAddressesper email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API. -
Optional. A list of carbon copy (CC) 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
toAddresses,ccAddresses, andbccAddressesper email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API. -
Optional. The character set for the email. If this value is null, the user’s default value is used.
-
setCustomHeaders(customHeaders)
Optional. Sets custom headers to include in the outgoing email. Each header name must be prefixed with
X-SFDC-X-. If a header name doesn’t have this prefix, Salesforce automatically adds it. Salesforce enforces this prefix to ensure security and compliance with internal protocols. All header names and values must comply with RFC 822 and RFC 5322 specifications. Avoid duplicate headers. -
setDocumentAttachments(documentIds)
(Deprecated. Use
setEntityAttachments()instead.) Optional. A list containing the ID of each document object you want to attach to the email. -
Optional. Array of IDs of Document, ContentVersion, or Attachment items to attach to the email.
-
Optional. A list containing the file names of the binary and text files you want to attach to the email.
-
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
setTemplateId,setHtmlBody, orsetPlainTextBody. Or, you can define bothsetHtmlBodyandsetPlainTextBody. -
setInReplyTo(parentMessageIds)
Sets the optional In-Reply-To field of the outgoing email. This field identifies the email or emails to which this email is a reply (parent emails).
-
Optional. If set to true, a List-Unsubscribe-Post header is added to an email with List-Unsubscribe=One-Click. Use this method to support unsubscribe functionality in email sent via Salesforce. You can provide additional instructions on how to send unsubscribe requests by using the header. This includes specifying the HTTP method and content type to use and provides a secure way to add more info to unsubscribe requests. Default is
false. -
setOptOutPolicy(emailOptOutPolicy)
Optional. If you added recipients by ID instead of email address and the
Email Opt Outoption is set, this method determines the behavior of thesendEmail()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. -
setPlainTextBody(plainTextBody)
Optional. The text version of the email, specified by the sender. Specify a value for
setTemplateId,setHtmlBody, orsetPlainTextBody. Or, you can define bothsetHtmlBodyandsetPlainTextBody. -
setOrgWideEmailAddressId(emailAddressId)
Optional. The ID of the organization-wide email address 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. The object’s
DisplayNamefield cannot be set if thesetSenderDisplayNamefield is already set. -
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.
-
Optional. The email subject line. If you are using an email template, the subject line of the template overrides this value.
-
setTargetObjectId(targetObjectId)
Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.
-
Required if using a template, optional otherwise. The ID of the template used to create the email.
-
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
toAddresses,ccAddresses, andbccAddressesper email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API. -
setTreatBodiesAsTemplate(treatAsTemplate)
Optional. If set to
true, the subject, plain text, and HTML text bodies of the email are treated as template data. The merge fields are resolved using therenderEmailTemplatemethod. Default isfalse. -
setTreatTargetObjectAsRecipient(treatAsRecipient)
Optional. If set to
true, thetargetObjectId(a contact, lead, or user) is the recipient of the email. If set tofalse, thetargetObjectIdis supplied as theWhoIdfield for template rendering but isn’t a recipient of the email. The default istrue. -
setUnsubscribeComment(unsubscribeComment)
Optional. Sets a comment in the List-Unsubscribe email header. This comment is ignored by email clients and systems that parse the header. The comments contain human-readable notes or context for developers, administrators, or other stakeholders managing the email system.
-
setUnsubscribeUrls(UnsubscribeUrls)
Optional. Sets a
mailtoURI and HTTP URL of a mechanism for unsubscribing a recipient from an email list. A list of all unsubscribe URLs passed throughsetUnsubscribeUrlsis added to theList-Unsubscribeheader. A minimum of one URL is required to use this method. -
If you specify a contact for the
targetObjectIdfield, you can specify an optionalwhatIdas well. This helps to further ensure that merge fields in the template contain the correct data.
Returns the map of custom headers previously set for the email. Returns null if no custom headers were set.
public Map<String,String> getCustomHeaders()
Type: Map<String,String>
Use this method to retrieve or verify the custom headers assigned to a Messaging.SingleEmailMessage object before sending.
Optional. Returns a boolean value based on the value set by the setOneClickPost method. Default is false.
public Boolean getOneClickPost()
Type: Boolean
Invoke the setOneClickPostmethod before using getOneClickPost. The value of getOneClickPost will be false if the setOneClickPostmethod is set to true only after invoking the setUnsubscribeUrls method.
The name of the template used to create the email.
public STRING getTemplateName()
Type: String
There is no equivalent setter method for getTemplateName(). If the email didn’t use a template, getTemplateName() returns nothing. If you use setTemplateId(), and then call getTemplateName(), the template name associated to the template ID is returned.
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 toAddresses, ccAddresses, and bccAddresses per email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API.
public Void setBccAddresses(String[] bccAddresses)
-
bccAddresses:
Type: String[]
Type: Void
All emails must have a recipient value in at least one of the following fields:
toAddressesccAddressesbccAddressestargetObjectId
If the BCC compliance option is set at the organization level, the user cannot add BCC addresses on standard messages. The following error code is returned: BCC_NOT_ALLOWED_IF_BCC_ COMPLIANCE_ENABLED. Contact your Salesforce representative for information on BCC compliance.
Optional. A list of carbon copy (CC) 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 toAddresses, ccAddresses, and bccAddresses per email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API.
public Void setCcAddresses(String[] ccAddresses)
-
ccAddresses:
Type: String[]
Type: Void
All emails must have a recipient value in at least one of the following fields:
toAddressesccAddressesbccAddressestargetObjectId
Optional. The character set for the email. If this value is null, the user’s default value is used.
public Void setCharset(String characterSet)
-
characterSet:
Type: String
Type: Void
Optional. Sets custom headers to include in the outgoing email. Each header name must be prefixed with X-SFDC-X-. If a header name doesn’t have this prefix, Salesforce automatically adds it. Salesforce enforces this prefix to ensure security and compliance with internal protocols. All header names and values must comply with RFC 822 and RFC 5322 specifications. Avoid duplicate headers.
public void setCustomHeaders(Map<String,String> customHeaders)
Type: Map<String,String>
Use this method to add metadata required for systems such as eSurveillance or eDiscovery. For example, to include the sending user’s address in a custom header, use the current user’s email and add it to the map. To meet RFC standards, ensure that your header values don’t contain invalid characters, such as newlines or control characters.
(Deprecated. Use setEntityAttachments() instead.) Optional. A list containing the ID of each document object you want to attach to the email.
public Void setDocumentAttachments(ID[] documentIds)
-
documentIds:
Type: ID[]
Type: Void
You can attach multiple documents as long as the total size of all attachments does not exceed 10 MB.
Optional. Array of IDs of Document, ContentVersion, or Attachment items to attach to the email.
public void setEntityAttachments(List<String> ids)
Type: void
Optional. A list containing the file names of the binary and text files you want to attach to the email.
public Void setFileAttachments(EmailFileAttachment[] fileNames)
-
fileNames:
Type: Messaging.EmailFileAttachment[]
Type: Void
You can attach multiple files as long as the total size of all attachments does not exceed 10 MB.
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 setTemplateId, setHtmlBody, or setPlainTextBody. Or, you can define both setHtmlBody and setPlainTextBody.
public Void setHtmlBody(String htmlBody)
-
htmlBody:
Type: String
Type: Void
Sets the optional In-Reply-To field of the outgoing email. This field identifies the email or emails to which this email is a reply (parent emails).
public Void setInReplyTo(String parentMessageIds)
-
parentMessageIds:
Type: String
Contains one or more parent email message IDs.
Type: Void
Optional. If set to true, a List-Unsubscribe-Post header is added to an email with List-Unsubscribe=One-Click. Use this method to support unsubscribe functionality in email sent via Salesforce. You can provide additional instructions on how to send unsubscribe requests by using the header. This includes specifying the HTTP method and content type to use and provides a secure way to add more info to unsubscribe requests. Default is false.
public void setOneClickPost(Boolean oneClickPost)
-
oneClickPost:
Type: Boolean
Type: void
You can set the oneClickPost method to true only after invoking the setUnsubscribeUrls method. If set to true, pass at least one HTTPS unsubscribe URL to unsubscribe.
This example demonstrates how to send an email using Salesforce’s Messaging.SingleEmailMessage class with enhanced unsubscribe functionality. It creates an email message with a recipient, subject, and body, and includes an unsubscribe URL. It also enables the oneClickPost feature, allowing for a simplified unsubscribe process. The email message is added to a list and sent using the Messaging.sendEmail method.
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.
public void setOptOutPolicy(String emailOptOutPolicy)
-
emailOptOutPolicy:
Type: String
Possible values of the emailOptOutPolicy parameter are:
SEND(default)—The email is sent to all recipients. The recipients’Email Opt Outsetting is ignored. The setting Enforce email privacy settings is ignored.FILTER—No email is sent to recipients that have theEmail Opt Outoption set. Emails are sent to the other recipients. The setting Enforce email privacy settings is ignored.REJECT—If any of the recipients have theEmail Opt Outoption 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.
Type: void
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.
Optional. The text version of the email, specified by the sender. Specify a value for setTemplateId, setHtmlBody, or setPlainTextBody. Or, you can define both setHtmlBody and setPlainTextBody.
public Void setPlainTextBody(String plainTextBody)
-
plainTextBody:
Type: String
Type: Void
Optional. The ID of the organization-wide email address 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. The object’s DisplayName field cannot be set if the setSenderDisplayName field is already set.
public Void setOrgWideEmailAddressId(ID emailAddressId)
-
emailAddressId:
Type: ID
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.
To avoid hard-coding an ID, after creating your org-wide email address, you can query them.
Type: Void
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.
public Void setReferences(String references)
-
references:
Type: String
Type: Void
Optional. The email subject line. If you are using an email template, the subject line of the template overrides this value.
public Void setSubject(String subject)
-
subject:
Type: String
Type: Void
Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.
public Void setTargetObjectId(ID targetObjectId)
-
targetObjectId:
Type: ID
Type: Void
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:
toAddressesccAddressesbccAddressestargetObjectId
Required if using a template, optional otherwise. The ID of the template used to create the email.
public Void setTemplateId(ID templateId)
-
templateId:
Type: ID
Type: Void
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 toAddresses, ccAddresses, and bccAddresses per email is 150. All recipients in these three fields count against the limit for email sent using Apex or the API.
public Void setToAddresses(String[] toAddresses)
-
toAddresses:
Type: String[]
Type: Void
All emails must have a recipient value in at least one of the following fields:
toAddressesccAddressesbccAddressestargetObjectId
Optional. If set to true, the subject, plain text, and HTML text bodies of the email are treated as template data. The merge fields are resolved using the renderEmailTemplate method. Default is false.
public void setTreatBodiesAsTemplate(Boolean treatAsTemplate)
-
treatAsTemplate:
Type: Boolean
Type: void
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.
public void setTreatTargetObjectAsRecipient(Boolean treatAsRecipient)
-
treatAsRecipient:
Type: Boolean
Type: void
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.
Optional. Sets a comment in the List-Unsubscribe email header. This comment is ignored by email clients and systems that parse the header. The comments contain human-readable notes or context for developers, administrators, or other stakeholders managing the email system.
public void setUnsubscribeComment(String unsubscribeComment)
-
unsubscribeComment:
Type: String
Type: void
Invoke the setUnsubscribeUrls method before using setUnsubscribeComment.
This example demonstrates how to send an email using Salesforce’s Messaging.SingleEmailMessage class with an option to include an unsubscribe link. It creates an email message with a recipient, subject, and body, and includes an unsubscribe URL that directs the recipient to send an unsubscribe request via email. Additionally, it sets an unsubscribeComment to provide context for the unsubscribe action.
Optional. Sets a mailto URI and HTTP URL of a mechanism for unsubscribing a recipient from an email list. A list of all unsubscribe URLs passed through setUnsubscribeUrls is added to the List-Unsubscribe header. A minimum of one URL is required to use this method.
public void setUnsubscribeUrls(List<String> unsubscribeUrls)
Type: void
Provide a list of URLs that support unsubscribe functionality by offering recipients multiple ways to opt-out of future communications. Each provided URL can use different protocols to allow for technical capacities of the recipient.
All setUnsubscribeUrls must have a value of one of these types:
-
Mailto: Allows recipients to send an unsubscribe request via email.- Example:
mailto:listrequest@example.com?subject=unsubscribe
- Example:
-
HTTP: Directs recipients to a web page where they can unsubscribe.- Example:
http://example.com/unsubscribe.html?opaque=123456789
- Example:
-
HTTPS: Directs recipients to a secure web page to unsubscribe.- Example:
https://example.com/unsubscribe.html?opaque=123456789
- Example:
This example demonstrates how to send an email using Salesforce’s Messaging.SingleEmailMessage class that includes an option to include an unsubscribe link for a user to click. It creates an email message, sets the recipient’s email address, subject, and body, and includes an unsubscribe URL. The email message is added to a list and sent using the Messaging.sendEmail method.
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.
public Void setWhatId(ID whatId)
-
whatId:
Type: ID
Type: Void
The value must be one of the following types:
- Account
- Asset
- Campaign
- Case
- Contract
- Opportunity
- Order
- Product
- Solution
- Custom