SingleEmailMessage Class
Namespace
Usage
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.
SingleEmailMessage Methods
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).
getOneClickPost()
Signature
public Boolean getOneClickPost()
Parameters
- Type: Boolean
Usage
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.
getTemplateName()
Signature
public STRING getTemplateName()
Return Value
Type: String
Usage
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.
setBccAddresses(bccAddresses)
Signature
public Void setBccAddresses(String[] bccAddresses)
Parameters
- bccAddresses
- Type: String[]
Return Value
Type: Void
Usage
- toAddresses
- ccAddresses
- bccAddresses
- targetObjectId
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.
setCcAddresses(ccAddresses)
Signature
public Void setCcAddresses(String[] ccAddresses)
Parameters
- ccAddresses
- Type: String[]
Return Value
Type: Void
Usage
- toAddresses
- ccAddresses
- bccAddresses
- targetObjectId
setCharset(characterSet)
Signature
public Void setCharset(String characterSet)
Parameters
- characterSet
- Type: String
Return Value
Type: Void
setDocumentAttachments(documentIds)
Signature
public Void setDocumentAttachments(ID[] documentIds)
Parameters
- documentIds
- Type: ID[]
Return Value
Type: Void
Usage
You can attach multiple documents as long as the total size of all attachments does not exceed 10 MB.
setEntityAttachments(ids)
Signature
public void setEntityAttachments(List<String> ids)
Return Value
Type: void
setFileAttachments(fileNames)
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)
Signature
public Void setHtmlBody(String htmlBody)
Parameters
- htmlBody
- Type: String
Return Value
Type: Void
setInReplyTo(parentMessageIds)
Signature
public Void setInReplyTo(String parentMessageIds)
Parameters
- parentMessageIds
- Type: String
- Contains one or more parent email message IDs.
Return Value
Type: Void
setOneClickPost(oneClickPost)
Signature
public void setOneClickPost(Boolean oneClickPost)
Parameters
- oneClickPost
- Type: Boolean
Return Value
Type: void
Usage
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.
Example
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.
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
// Set the recipient's email address
// Replace IDs with valid record IDs in your org.
message.toAddresses = new String[] { '003D000000QDexS' };
message.subject = 'Test Message';
message.plainTextBody = 'This is the message body.';
// Create a list to hold unsubscribe URLs
List<String> unsubscribeUrls = new List<String>();
unsubscribeUrls.add('https://example.com/unsubscribe.html?opaque=123456789');
// Assign the unsubscribe URLs to the email message
message.unsubscribeUrls = unsubscribeUrls;
// Enable the one-click unsubscribe feature
message.oneClickPost = true;
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);
}
setOptOutPolicy(emailOptOutPolicy)
Signature
public void setOptOutPolicy(String emailOptOutPolicy)
Parameters
- emailOptOutPolicy
- Type: String
- 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.
Return Value
Type: void
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);
}
setPlainTextBody(plainTextBody)
Signature
public Void setPlainTextBody(String plainTextBody)
Parameters
- plainTextBody
- Type: String
Return Value
Type: Void
setOrgWideEmailAddressId(emailAddressId)
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.
To avoid hard-coding an ID, after creating your org-wide email address, you can query them.
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);
}
Return Value
Type: Void
setReferences(references)
Signature
public Void setReferences(String references)
Parameters
- references
- Type: String
Return Value
Type: Void
setSubject(subject)
Signature
public Void setSubject(String subject)
Parameters
- subject
- Type: String
Return Value
Type: Void
setTargetObjectId(targetObjectId)
Signature
public Void setTargetObjectId(ID targetObjectId)
Parameters
- targetObjectId
- Type: ID
Return Value
Type: Void
setTemplateId(templateId)
Signature
public Void setTemplateId(ID templateId)
Parameters
- templateId
- Type: ID
Return Value
Type: Void
setToAddresses(toAddresses)
Signature
public Void setToAddresses(String[] toAddresses)
Parameters
- toAddresses
- Type: String[]
Return Value
Type: Void
Usage
- toAddresses
- ccAddresses
- bccAddresses
- targetObjectId
setTreatBodiesAsTemplate(treatAsTemplate)
Signature
public void setTreatBodiesAsTemplate(Boolean treatAsTemplate)
Parameters
- treatAsTemplate
- Type: Boolean
Return Value
Type: void
setTreatTargetObjectAsRecipient(treatAsRecipient)
Signature
public void setTreatTargetObjectAsRecipient(Boolean treatAsRecipient)
Parameters
- treatAsRecipient
- Type: Boolean
Return Value
Type: void
Usage
setUnsubscribeComment(unsubscribeComment)
Signature
public void setUnsubscribeComment(String unsubscribeComment)
Parameters
- unsubscribeComment
- Type: String
Return Value
Type: void
Usage
Invoke the setUnsubscribeUrls method before using setUnsubscribeComment.
Example
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.
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
// Set the recipient's email address
// Replace IDs with valid record IDs in your org
message.toAddresses = new String[] { '003D000000QDexS' };
message.subject = 'Test Message';
message.plainTextBody = 'This is the message body.';
// Create a list to hold unsubscribe URLs
List<String> unsubscribeUrls = new List<String>();
unsubscribeUrls.add('mailto:listrequest@example.com?subject=unsubscribe');
// Assign the unsubscribe URLs to the email message
message.unsubscribeUrls = unsubscribeUrls;
// Set an unsubscribe comment to provide context for the unsubscribe action
message.unsubscribeComment = 'email unsubscribe support';
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);
}
setUnsubscribeUrls(UnsubscribeUrls)
Signature
public void setUnsubscribeUrls(List<String> unsubscribeUrls)
Return Value
Type: void
Usage
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
-
HTTP: Directs recipients to a web page where they
can unsubscribe.
- Example: http://example.com/unsubscribe.html?opaque=123456789
-
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.
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
// Set the recipient's email address
// Replace IDs with valid record IDs in your org.
message.toAddresses = new String[] { '003D000000QDexS' };
message.subject = 'Test Message';
message.plainTextBody = 'This is the message body.';
// Create a list to hold unsubscribe URLs
List<String> unsubscribeUrls = new List<String>();
unsubscribeUrls.add('https://example.com/unsubscribe.html?opaque=123456789');
// Assign the unsubscribe URLs to the email message
message.unsubscribeUrls = unsubscribeUrls;
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);
}
setWhatId(whatId)
Signature
public Void setWhatId(ID whatId)
Parameters
- whatId
- Type: ID
Return Value
Type: Void
Usage
The value must be one of the following types:
- Account
- Asset
- Campaign
- Case
- Contract
- Opportunity
- Order
- Product
- Solution
- Custom