Last active
July 5, 2017 17:29
-
-
Save sohalloran/0b6f8eca10a0d236227f03f58fe6ad60 to your computer and use it in GitHub Desktop.
Email2Case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global class Email2Case implements Messaging.InboundEmailHandler { | |
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) { | |
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult(); | |
String body = email.plainTextBody; | |
Case newCase = new Case(); | |
newCase.SuppliedEmail = parse(body,'EMAIL:',false); | |
newCase.SuppliedName = parse(body,'LAST NAME:',false); | |
newCase.Description = 'Accepted Terms: ' + parse(body,'ACCEPTED TERMS',false) + ' Receive Further Info: ' + parse(body,'RECEIVE FURTHER INFO',false) + ' ' + parse(body,'MESSAGE:',true); | |
newCase.Subject = 'Email from ' + parse(body,'EMAIL:',false); | |
insert newCase; | |
return result; | |
} | |
private static String parse(String body, String label, boolean multiline) { | |
String multilineStr = multiline?'(?s)':''; | |
String regex = multilineStr + '(?m)^\\s*'+label+'\\s+(.*)$'; | |
String retVal = ''; | |
Matcher m = Pattern.compile(regex).matcher(body); | |
if (m.find()) { | |
retVal = m.group(1); | |
} | |
return retVal; | |
} | |
} | |
// TEST CLASS | |
@isTest | |
private class Email2CaseTest { | |
static testMethod void testEmail2Case() { | |
// create a new email and envelope object | |
Messaging.InboundEmail email = new Messaging.InboundEmail() ; | |
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); | |
// setup the data for the email | |
email.subject = 'Test Job Applicant'; | |
email.fromname = 'FirstName LastName'; | |
email.plainTextBody = '\n\nSALUTATION: {{Title}}\n\nFIRST NAME: Joe\n LAST NAME: Smith \n EMAIL: [email protected] \n ACCEPTED TERMS: yes \n RECEIVE FURTHER INFO: yes\n\n \n MESSAGE:\n some message \n\n'; | |
env.fromAddress = '[email protected]'; | |
// call the email service class and test it with the data in the testMethod | |
Email2Case e2c = new Email2Case(); | |
e2c.handleInboundEmail(email, env); | |
// query for the contact the email service created | |
Case newCase = [select id, SuppliedEmail from case where SuppliedEmail = '[email protected]']; | |
System.assertEquals(newCase.SuppliedEmail,'[email protected]','Expected the case to be created and the email to match'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment