Sending Email

The three ways to send email in Apex are the following:

Image SingleEmailMessageSends an email to up to ten receivers. The email addresses of receivers are provided as strings. A string containing HTML or plain text is used as the message body.

Image SingleEmailMessage with template—Sends to up to ten receivers, but the unique identifiers of Contact, Lead, or User objects must be used instead of strings to provide the receivers’ email addresses. The message body is constructed from a template. Templates are globally available to an organization as defined by an administrator or private to an individual user. Templates can include merge fields to dynamically substitute field values from the receiver’s record and, optionally, field values from an additional, related object.

Image MassEmailMessageBehaves like a SingleEmailMessage with template but can send email to up to 250 receivers in a single call.

Each of these three ways of sending email contributes toward the maximum of 10 email calls within a single context, an instance of running Apex code. To translate that to the number of email messages, if you use the SingleEmailMessage object with 10 recipients, you can reach a maximum of 100 recipients (10 recipients times the 10 invocation maximum) within a single execution of your program. You can reach 2,500 recipients using the MassEmailMessage. Force.com imposes a daily limit on mass emails, which varies based on the edition of Force.com being used. If this limit is exceeded, an exception is thrown with the exception code MASS_MAIL_LIMIT_EXCEEDED.

Using SingleEmailMessage

You can run the code in Listing 5.24 directly in the Execute Anonymous view. It looks up the User record for the current user and sends a test message to its email address.

Listing 5.24 Sending Email


User you = [ SELECT Email
  FROM User
  WHERE Id = :UserInfo.getUserId()
  LIMIT 1 ];
Messaging.SingleEmailMessage mail =
  new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] { you.Email });
mail.setSubject('Test message'),
mail.setPlainTextBody('This is a test'),
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


Check the email account associated with your Force.com user for the new message. If you do not see the message, it might be in your junk mail folder. If it’s not in your inbox or junk mail folder, your email server might have refused its delivery. In this case, Force.com will send you the returned message with any delivery error information, given that you are both the sender and the receiver.


Note

Force.com provides online tools to help you authorize its mail servers to ensure that its messages are delivered. Go to the Administration Setup area and click Email Administration, Deliverability and Test Deliverability for more information.


Notice that the sender and receiver of the email are identical. You have sent a message to yourself via Force.com. By default, Apex email methods run using the identity of the current user. The current user’s email address becomes the “from” address in outbound emails. Alternatively, you can define an organization-wide email address and use it to set the “from” address. This enables all of your outbound emails to be sent from a single set of authorized, public email addresses. To define an organization-wide email address, go to the Administration Setup area and click Email Administration, Organization-Wide Addresses.

Using SingleEmailMessage with Template

Templates standardize the appearance and content of emails. They also make including dynamic content in messages without cumbersome, hard-to-maintain code full of string concatenations simple. To add a new email template, go to the Personal Setup area and click Email, My Templates.

When a template is used to send a message, you must provide a targetObjectId value. This is the unique identifier of a Lead, Contact, or User record. The email address associated with this record becomes the recipient of the email.

Optionally, a whatId can be provided. This is the unique record identifier of an Account, Asset, Campaign, Case, Contract, Opportunity, Order, Product, Solution, or any custom object. The fields from this record can be referenced in your template using merge fields. When the message is sent, the record is retrieved and its data substituted into the message body in the locations specified by the merge fields.

Listing 5.25 sends an email using a template. Before trying it, create a template with the unique name of Test_Template. Set its text or HTML content to Hello {!User.FirstName}! or the equivalent to demonstrate the use of merge fields. Mark the template as available for use. In Listing 5.25, a SOQL query is used to retrieve the template’s unique identifier so that it isn’t hard-coded into the program.

Listing 5.25 Sending Email Using a Template


User you = [ SELECT Email
  FROM User
  WHERE Id = :UserInfo.getUserId()
  LIMIT 1 ];
EmailTemplate template = [ SELECT Id
  FROM EmailTemplate
  WHERE DeveloperName = 'Test_Template'
  LIMIT 1 ];
Messaging.SingleEmailMessage mail =
  new Messaging.SingleEmailMessage();
mail.templateId = template.Id;
mail.targetObjectId = you.Id;
mail.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });



Note

The setSaveAsActivity method was called in Listing 5.25 to disable the HTML email tracking feature, which is not compatible with the User object (targetObjectId). The setSaveAsActivity method is described in the upcoming subsection, “Additional Email Methods.”


Using MassEmailMessage

Mass emails can be sent to 250 recipients in a single method call. The code for sending a mass email is similar to that for sending a single email with a template. The difference is that a MassEmailMessage object is created instead of a SingleEmailMessage. At minimum, you must provide a value for targetObjectIds (an array of Lead, Contact, or User record unique identifiers) and a templateId.

Optionally, you can provide whatIds, an array of record unique identifiers corresponding to the array of targetObjectIds. Field values from these records add dynamic content to the message body. The records are limited to Contract, Case, Opportunity, and Product types. Note that none of these object types are available in a Force.com platform-only license.

Listing 5.26 demonstrates the use of the MassEmailMessage. It selects one Contact in the system and sends an email using the same template created for Listing 5.25.

Listing 5.26 Sending a Mass Email


User you = [ SELECT Email
  FROM User
  WHERE Id = :UserInfo.getUserId()
  LIMIT 1 ];
EmailTemplate template = [ SELECT Id
  FROM EmailTemplate
  WHERE DeveloperName = 'Test_Template'
  LIMIT 1 ];
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
mail.templateId = template.Id;
mail.targetObjectIds = new Id[] { you.Id };
mail.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });


Transactional Email

The transactional behavior of the sendEmail method is consistent with that of Force.com database DML methods. When an invocation of Apex code is completed without error, email is sent. If an uncaught error causes the program to be terminated prematurely, email is not sent. If multiple emails are sent, by default they all fail if one fails. Setting the optional opt_allOrNone parameter of the sendEmail method to false enables partial success of a group of outbound messages. In this case, the sendEmail method returns an array of SendEmailResult objects. These objects can be used to determine the success or failure of each message and include error details in case of failure.

Additional Email Methods

The following list describes useful methods that apply to both SingleEmailMessage and MassEmailMessage objects:

Image setCcAddressesThis method accepts a string array of email addresses to carbon copy on the email.

Image setSenderDisplayNameThe sender display name is shown in email reading programs as a label for the sender email address.

Image setReplyToThe reply-to address is the email address designated to receive replies to this message. If not specified, it’s always the sender’s email address.

Image setBccSenderIf this is set to true, Force.com blind-carbon-copies the sender’s email address. In a mass email, the sender is copied only on the first message. Force.com prevents use of this feature if an administrator has enabled Compliance BCC Email. You can do this in the Administration Setup area by clicking Email Administration, Compliance BCC Email.

Image setUseSignatureBy default, Force.com appends the sending user’s signature to the end of outbound emails. You can edit this signature in the Personal Setup area by clicking Email, My Email Settings. To turn off this feature, pass false to this method.

Image setFileAttachmentsThe argument to this method is an array of EmailFileAttachment objects. These objects contain the names and data of attachments to be sent with the message. They provide a method to set the attachment body (setBody) and filename (setFileName). The total size of the attachments for a single message cannot exceed 10MB.

Image setDocumentAttachmentsForce.com has a native object type for storing content called Document. You can find it in the native user interface by clicking the Documents tab. Here you can create, edit, and delete Documents and group them into folders. Each Document record has a unique identifier, and this method accepts an array of them. Each Document specified is sent as an attachment to the message. All attachments in a single message, including file attachments, cannot exceed 10MB.

Image setOrgWideEmailAddressIdUse this method to specify the unique identifier of an organization-wide email address. This email address is used as the “from” address rather than the address of the current user. To define organization-wide email addresses and obtain their unique identifiers, go to the Administration Setup area and click Email Administration, Organization-Wide Addresses.

Image setSaveAsActivityForce.com’s outbound email can be configured to track the behavior of email recipients who are Leads or Contacts in the system. This is accomplished with an invisible image embedded in messages sent using templates. When receivers who haven’t blocked multimedia content in their email readers open the message, the Force.com service is contacted and tracks this information. By visiting the receiver’s Lead or Contact record, you can see the date the email was first opened, the number of times it was opened, and the date it was most recently opened. By default, this setting is enabled. To disable or enable it for the organization, go to the App Setup area and click Customize, Activities, Activity Settings and select Enable Email Tracking. To disable it for a specific message, pass false to this method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.194