Use Email Services for Customized Email-to-Case Email Services is a great tool.  Sometimes called Email-to-Apex, it allows for the ability to create an email address within Salesforce that can kick off and process Apex code.  Setting up the email service address is quite simple; an overview can be found here on how to set it up.  There are a number of security and functionality options that can be handled declaratively, for example:

  • Whitelisting of email addresses (or domains) that the email address accepts from.
  • Handling of attachments
  • Failure/Error handling
  • Selection of a context user that’s associated with the email address and Apex Class

I want to share one particular use case where the email service was really handy; it’s a customized Email-to-Case situation.  While the standard email-to-case functionality within Salesforce makes it easy to create cases from incoming emails, all point-and-click which is great, it obviously lacks some abilities.

This example is a bit unique in that the organization’s parent company captured information from a form on their website and forwarded it via an email.  There are only two types of emails being sent to this address, so the subject lines and the exact format of the text emails were known in advance. Let’s say the emails look like this…

Hi, you have received this email from your parent company.
The following person has created a case.

Name: Joe Test
Role: Owner
Phone: 555-555-5555
City: Anytown
Region: Georgia
Country: USA

What seems to be the problem?  "This is where Joe would write his problem."

The requirements in this situation were a) the ability to parse the emails for contact info; b) the ability to create a new contact if this was not someone currently in the database; c) to relate the new contact to a specific catch-all account; and d) to create a case (and populate fields in the case), then relate the case to the contact.

Below is the example code for creating this email service. Names have been changed to protect the innocent:

   global class CustomEmailToCase implements Messaging.InboundEmailHandler {

       // Instantiate variables that we will need for handling this email
        public Contact cnt;
        public Case sCase;
        public String name;
        public String role;
        public String emailAddress;
        public String phone;
        public String city;
        public String region;
        public String country;
        public Integer nameIdx;
        public Integer roleIdx;
        public Integer emailAddressIdx;
        public Integer phoneIdx;
        public Integer cityIdx;
        public Integer regionIdx;
        public Integer countryIdx;
        public String nameFinal;
        public String roleFinal;
        public String emailFinal;
        public String phoneFinal;
        public String cityFinal;
        public String regionFinal;
        public String countryFinal;

     global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

          if (email.subject =='Email Subject 1' || email.subject == 'Email Subject 2') {
          // Set variables that will be used to locate the indexes
          name = 'Name: ';
          role = 'Role: ';
          emailAddress = 'Email: ';
          phone = 'Phone: ';
          city = 'City: ';
          region = 'Region: ';
          country = 'Country: ';

          // Create the indexes for the beginning of each piece of contact info we need.
          // This is the first step in parsing the email to extract the Contact Info
          nameIdx = email.plainTextBody.indexOf(name);
          roleIdx = email.plainTextBody.indexOf(role);
          emailAddressIdx = email.plainTextBody.indexOf(emailAddress);
          phoneIdx = email.plainTextBody.indexOf(phone);
          cityIdx = email.plainTextBody.indexOf(city);
          regionIdx = email.plainTextBody.indexOf(region);
          countryIdx = email.plainTextBody.indexOf(country);

          // Using the above indexes, find the starting point within the email for each piece of contact info,
          // then grab everything from that index to the end of that line and store it in a new variable.
          // This is the second part of parsing the email to extract the Contact Info.

          nameFinal = email.plainTextBody.substring(
                              nameIdx + name.length(), email.plainTextBody.indexOf('\n', nameIdx + name.length()));
          String[] cntNme = nameFinal.split(' ', 3);
          roleFinal = email.plainTextBody.substring(
                              roleIdx + role.length(), email.plainTextBody.indexOf('\n', roleIdx + role.length()));
          emailFinal = email.plainTextBody.substring(
                              emailAddressIdx + emailAddress.length(), email.plainTextBody.indexOf('\n', emailAddressIdx + emailAddress.length()));
          phoneFinal = email.plainTextBody.substring(
                              phoneIdx + phone.length(), email.plainTextBody.indexOf('\n',phoneIdx + phone.length()));
          cityFinal = email.plainTextBody.substring(
                              cityIdx + city.length(), email.plainTextBody.indexOf('\n', cityIdx + city.length()));
          regionFinal = email.plainTextBody.substring(
                              regionIdx + region.length(), email.plainTextBody.indexOf('\n', regionIdx + region.length()));
          countryFinal = email.plainTextBody.substring(
                              countryIdx + country.length(), email.plainTextBody.indexOf('\n', countryIdx + country.length()));

          // Using the email address from above, query the database for a matching Contact.
          if (emailFinal.length() > 0) {
            Contact [] contactArray = [Select Id, Email, AccountId from Contact where Email =: emailFinal limit 1];

             // If the contact is a match, create a case and relate it to the Contact.
             if (contactArray.size() > 0) {
               sCase = new Case();
               sCase.ContactId = contactArray[0].Id;
               sCase.AccountId = contactArray[0].AccountId;
               sCase.Status = 'New';
               sCase.Type = 'BD';
               sCase.Origin = 'Email';
               sCase.Priority = 'Medium';
               sCase.Subject = email.subject;
               sCase.Description = email.plainTextBody;
               sCase.OwnerId = 'xxxxxxxxxxxxxxxx';

               try {
                 insert sCase;
               } catch (System.DmlException e)
                   {System.debug('ERROR: Not able to create Case: ' + e);

             // If the contact is NOT a match, first create the Contact then create a Case related to the contact.

             if (contactArray.size() == 0 || contactArray.size() == null) {
               cnt = new Contact();
               cnt.AccountId = 'xxxxxxxxxxxxxxxx';
               cnt.FirstName = cntNme.get(0);
               cnt.LastName = cntNme.get(1);
               cnt.Email = emailFinal;
               cnt.Phone = phoneFinal;
               cnt.Title = roleFinal;
               cnt.MailingCity = cityFinal;
               cnt.MailingState = regionFinal;
               cnt.OwnerId = 'xxxxxxxxxxxxxxxx';

               try {
                 insert cnt;
               }  catch (System.Dmlexception e)
                    {System.debug('Error: Not able to create new Contact: ' + e);
                sCase = new Case();
                sCase.ContactId =;
                sCase.AccountId = 'xxxxxxxxxxxxxxxx';
                sCase.Status = 'New';
                sCase.Type = 'BD';
                sCase.Origin = 'Email';
                sCase.Priority = 'Medium';
                sCase.Subject = email.subject;
                sCase.Description = email.plainTextBody;
                sCase.OwnerId = 'xxxxxxxxxxxxxxxx';

                try {
                  insert sCase;
                }  catch (System.Dmlexception e)
                     {System.debug('Error: Not able to create new Case: ' + e);

            // If no email address is gathered from the email body, write to the debug log, and no actions
            // will be performed.
           else if (emailFinal == null || emailFinal.length() == 0){
              System.debug('No email address was found.');

          return result;

      } // Close handleInboundEmail ()

    //Test Methods

    static testmethod void myEmailTest1 () {

      //Test #1 - Create New Contact and add Case

          // Create a new email, envelope object and Attachment
           Messaging.InboundEmail email = new Messaging.InboundEmail();
           Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
           String n = '\n';

           env.fromAddress = '';
           email.subject = 'Email Subject 1';
           email.plainTextBody = 'Name: Joe Test'+ n +
                                  'Role: Owner' + n +
                                  'Email:' + n +
                                  'Phone: 555-555-5555' + n +
                                  'City: TestCity' + n +
                                  'Region: Georgia' + n +
                                  'Country: USA' + n ;

           // call the class and test it with the data in the testMethod
           CustomEmailToCase emailServiceObj = new CustomEmailToCase();
           emailServiceObj.handleInboundEmail(email, env );

static testmethod void myEmailTest2 () {

   //Test #2 - Attaching Case to Matching Contact

   Messaging.InboundEnvelope env2 = new Messaging.InboundEnvelope();
   // first create and insert contact
   // test with a matching contact
   Messaging.InboundEmail email2 = new Messaging.InboundEmail();
   Contact c = new Contact();
   c.FirstName = 'Test';
   c.LastName = 'Test';
   c.Email = '';
   insert c;

   // create email body using above email address
   env2.fromAddress = '';
   email2.subject = 'Email Subject 1';
   email2.plainTextBody = 'Name: Test Test'+ n +
   'Role: Owner' + n +
   'Email:' + n +
   'Phone: 555-555-5555' + n +
   'City: TestCity' + n +
   'Region: Georgia' + n +
   'Country: USA' + n ;

   //call the class and test it with the data
   CustomEmailToCase emailServiceObj2 = new CustomEmailToCase();
   emailServiceObj2.handleInboundEmail(email2, env2);

static testmethod void myEmailTest3 () {

   //Test #3 - Test with invalid fromAddress

   Messaging.InboundEnvelope env3 = new Messaging.InboundEnvelope();

   // this from address isn't on our whitelist so it shouldn't trigger any code
   env.fromAddress = '';
   email3.subject = 'Spam';
   email3.plainTextBody = 'Name: Test Test'+ n +
   'Role: Owner' + n +
   'Email:' + n +
   'Phone: 555-555-5555' + n +
   'City: TestCity' + n +
   'Region: Georgia' + n +
   'Country: USA' + n ;

   // test incoming email that is not valid
   Messaging.InboundEmail email3 = new Messaging.InboundEmail();

   // call the class and test it with the data
   CustomEmailToCase emailServiceObj3 = new CustomEmailToCase();
   emailServiceObj3.handleInboundEmail(email3, env3);

 static testmethod void myEmailTest4 () {

   //Test #4 - Test with blank Email field

   Messaging.InboundEmail email4 = new Messaging.InboundEmail();
   Messaging.InboundEnvelope env4 = new Messaging.InboundEnvelope();

   // Use a blank email address
   env.fromAddress = '';
   email3.subject = 'Email Subject 1';
   email3.plainTextBody = 'Name: Test Test'+ n +
   'Role: Owner' + n +
   'Email: ' + n +
   'Phone: 555-555-5555' + n +
   'City: TestCity' + n +
   'Region: Georgia' + n +
   'Country: USA' + n ;

   // call the class and test it with the data
   CustomEmailToCase emailServiceObj4 = new CustomEmailToCase();
   emailServiceObj4.handleInboundEmail(email4, env4);

} // Close Class
No comments yet.

Leave a Reply