Welcome!

CRM Authors: Xenia von Wedel, Ian Khan, PR.com Newswire, Steve Mordue

Related Topics: CRM

CRM: Case Study

Use Email Services for Customized Email-To-Case

With Code

Force.com 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
Email: joetest@joetest.com
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 = cnt.id;
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 = 'thisEmailIsOk@gooogle.com';
email.subject = 'Email Subject 1';
email.plainTextBody = 'Name: Joe Test'+ n +
'Role: Owner' + n +
'Email: test@email.com' + 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 = 'testing@testing.com';
insert c;

// create email body using above email address
env2.fromAddress = 'thisEmailIsOk@gooogle.com';
email2.subject = 'Email Subject 1';
email2.plainTextBody = 'Name: Test Test'+ n +
'Role: Owner' + n +
'Email: testing@testing.com' + 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 = 'test@test.com';
email3.subject = 'Spam';
email3.plainTextBody = 'Name: Test Test'+ n +
'Role: Owner' + n +
'Email: testing@testing.com' + 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 = 'thisEmailIsOk@gooogle.com';
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

More Stories By Clint Lee

Clint is a Principal and Founder of The Flywheel Group, a premier provider of innovative solutions to the franchise industry. The FranchiseFlywheel™ application was developed out of the industry's need for a cutting-edge and affordable franchise management tool for franchisors. Spending several years in the franchise industry directing daily activities related to franchise and business development processes, marketing, lead-generation, and contract administration, and an understanding of the needs of peers and colleagues, led to the development of the application. The Flywheel Group is focused on improving best practices and driving change in the franchise industry by introducing industry-leading solutions and working with its clients to re-engineer business processes that will ultimately enhance revenue and improve bottom line efficiency. Clint actively writes and shares his thoughts on the Flywheel Blog.

IoT & Smart Cities Stories
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
In this Women in Technology Power Panel at 15th Cloud Expo, moderated by Anne Plese, Senior Consultant, Cloud Product Marketing at Verizon Enterprise, Esmeralda Swartz, CMO at MetraTech; Evelyn de Souza, Data Privacy and Compliance Strategy Leader at Cisco Systems; Seema Jethani, Director of Product Management at Basho Technologies; Victoria Livschitz, CEO of Qubell Inc.; Anne Hungate, Senior Director of Software Quality at DIRECTV, discussed what path they took to find their spot within the tec...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear these words all day every day... lofty goals but how do we make it real? Add to that, that simply put, people don't like change. But what if we could implement and utilize these enterprise tools in a fast and "Non-Disruptive" way, enabling us to glean insights about our business, identify and reduce exposure, risk and liability, and secure business continuity?
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.