ANJARGHOLI.COM

Yolande Anjargholi Online

Salesforce.com is the Lamborghini of CRM systems, and one of the most essential features of any top rated CRM system, is the sending and tracking of emails. If you are someone that works with salesforce.com in any technical capacity, it is important to have some ‘under the hood’ insight around the capabilities, limitations, and monitoring abilities you have at your disposable, when working with outbound email.  While using workflow or some of the OOB email features may be more familiar to all of us ‘none hard-core’ developers, and admins, it can be very helpful to be more equip with some additional insight, about how APEX can be used to send emails from Salesforce.  If you haven’t already, you are bound to encounter situations where coding is needed to send out an e-mail.

BASIC OVERVIEW

Depending on your requirements, you can send emails programmatically to one, or multiple people. E-mail recipients can either exist as a record in your Salesforce organization (ex. Lead, Contact, Person Account, or User records), or can be any other internal or external individual. You also have the ability to send a single email, or to send mass emails.  Salesforce essentially offers two classes that you can leverage, depending on what you are trying to accomplish: 

>>Send Individual Emails

** APEX Class: SingleEmailMessage 
** Format Options: HTML, Plain text, Salesforce email templates, generated by Visualforce
** Other Considerations: You can send 100 emails per SingleEmailMessage 

>> Send Mass Emails

** APEX Class: MassEmailMessage
** Format Options: HTML, Plain text, Salesforce email templates, (Visualforce email templates are NOT available)
** Other Considerations: You can send mass emails only to contacts, person accounts, leads, and your org’s internal users

GOVERNOR LIMITS

>> VIA UI
Single emails sent using the Salesforce application don't count toward this limit. There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly   from account, contact, lead, opportunity, case, campaign, or custom object pages.

>> VIA API/APEX

This is where it gets a little tricky.

- You can send single emails to a maximum of 1,000 external email addresses per day based on Greenwich Mean Time (GMT)
- Depending on what edition you are using, you can send mass email to a maximum of 1,000 external email addresses per day per org based on Greenwich Mean Time (GMT)

(See the useful links section at the bottom of this post, for easy navigation to the Salesforce quick reference documentation on e-mail limits)

With that said -  if you have code that send an email to a Salesforce user, lead, or contact (i.e. internal to your salesforce organization), you / your dev team should always try to opt for using the ‘TargetObjectID’, instead of using / referencing an actual e-mail address (ex. UserInfo.getUserEmail’). By following this approach, ‘internal’ emails are NOT counted against the limit. Ideally, we want to have all 1000 emails available for when / if we need to send emails to external parties or ‘non-salesforce records’ via the API/APEX. I will include a sample code towards the end of this post, that you copy and use, to try this out, for yourself.

Note - single and mass email limits don't take unique addresses into account, so when you include, for example, This email address is being protected from spambots. You need JavaScript enabled to view it. in your email, 10 times, that will actually count as 10, towards the limit. 

CHECKING YOUR LIMITS / LOGS

When it comes time to take a closer look at the e-mails that have been sent from your Salesforce org, I have found these 3 options, useful:

  1. Check on your remaining / available emails, based on limits for SingleEmailMessage and MassEmailMessage: click here for knowledge article with step by step instructions.
    Checking Email Limit Utalization
  2. Email logs are CSV files that can be requested, and contain information about all email sent through your Salesforce organization over the last 30 days. You can request these logs from setup, without help from Salesforce, and it generates fairly quickly. Click here for step by step instructions on how to get your email logs.

  3. Salesforce can track the status of email in HTML format, including the date the email was sent, first opened and last opened, and the total number of times it was opened. You will need to have e-mail tracking enabled for your organization (Setup | Customize | Activities | Activity Settings | Email Tracking checkbox)  

    When you do, you will have access to the following reporting / tracking features:

    a)Report Type: HTML Email Status Report (for contacts)
    b)Report Fields: when creating normal account and contacts reports, you should have these 2 fields available, to add to your reports: ‘Email      Bounced Reason’, and ‘Email Bounced Date’. 
    c) Related List: You can add the ‘HTML Email Status’ related list to your Lead, Contact, or Person Account page layouts.

           HTML Email Status Related List

TRY IT OUT - SAMPLE CODE

From your developer console, click File | New | Apex Class. Remove any markup you see on the page, and then Copy and paste the code below. You should chnage Peter Pan, and Tinker Bell's email addresses, to a valid email address that you are able to check. 


public class EmailExample {
    public void sendExternalEmailMessage() {
        //will count against your limit, even if we set the toAddress to 'UserInfo.getUserEmail’
        //or to an internal user email that is not a salesforce user in your organization
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		String[] toAddresses = new String[] {'This email address is being protected from spambots. You need JavaScript enabled to view it.', 'This email address is being protected from spambots. You need JavaScript enabled to view it.'}; 
		mail.setToAddresses(toAddresses);
		mail.setSubject('This is the subject');
		mail.setPlainTextBody('This is the body');

        // Send the email you have created.
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
    public void sendInternalEmailMessage() {
        //sending to salesforce user
        //will NOT count against limit because we are using 'setTargetObjectId'
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		mail.setTargetObjectId(UserInfo.getUserId());
		mail.setSubject('Mary - This is the subject for an email sent to a salesforce user');
		mail.setPlainTextBody('This is the body for an email sent to a salesforce user');
        //when sending mail to users, you have to set this switch to false
        mail.setSaveAsActivity(false);

        // Send the email you have created.
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
    public void sendInternalEmailUsingTemplate() {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		mail.setTargetObjectId(UserInfo.getUserId());
		mail.setTemplateId('00Xi0000000KyBW');
        //when sending mail to users, you have to set this switch to false
        mail.setSaveAsActivity(false);

        // Send the email you have created.
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });                       
    }
}

Note - this code is not intended for production, as you may need to enhance/ improve on it, before you use it in a production environment.  
Once you saved, you can test this out, but running the methods in your class:
>From the dev console, click Debug | Open Execute Anonymous Window
> Copy the code below, into the window that opened, and click on execute

EmailExample sendmail = new EmailExample();
sendmail.sendExternalEmailMessage();
sendmail.sendInternalEmailMessage();
sendmail.sendInternalEmailUsingTemplate();

USEFUL LINKS

SingleEmailMessage - Developer Guide Link for all Methods of this class 
> MassEmailMessage (Developer Guide Link for all Methods of this class 
> API / APEX Email Limits
Knowledge Article on how to monitor Email limit utilization
> APEX CODE TIP – Sending Email to Salesforce Users
> Integrating Email with VisualForce
> Salesforce HTML Email Tracking Explained
> Was my emails delivered and opened