Friday, March 20, 2015

Salesforce: Apex Email Service To Create Cases

Sometimes we have to create case form custom email formats. Sales force provides a Apex interface to process inbound emails.

1. Create Apex Class

      Create an Apex class to parse the email content and create case as per your business logic.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
global class CustomEmailCase implements Messaging.InboundEmailHandler {

     global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
           //sendTestMail('plain'+email.plainTextBody);
           //sendTestMail('html'+email.htmlBody);
         // if (email.subject == 'subject1' || email.subject == 'Email Subject 2') {
          //sendTestMail(email.plainTextBody);
              /* Email Format - Plaint text body
                       NAME:       Riyas basheer
     PHONE:          0398489724
     EMAIL:          riyas@google.co.in
              */ 
              
              String pName = this.parseEmailContent(email.plainTextBody, 'NAME: ');
              String pEmail = this.parseEmailContent(email.plainTextBody, 'EMAIL: ');
              String pPhone  = this.parseEmailContent(email.plainTextBody, 'PHONE: ');
    
              // Using the email address from above, query the database for a matching Contact.
              if (pEmail.length() > 0) {
                Contact [] contactArray ;
                Case emailCase = new Case();
                for(Contact caseContact:[SELECT Id, Email, AccountId FROM Contact WHERE Email =: pEmail LIMIT 1]){
                
                   emailCase.ContactId = caseContact.Id;
                   emailCase.AccountId = caseContact.AccountId;
                }
               emailCase.Status = 'New';
               emailCase.Origin = 'the orgin';
               emailCase.Priority = 'Medium';
               emailCase.Type = 'my type';
               emailCase.Subject = ' '+email.subject;
               emailCase.p_Name__c = pName;
               emailCase.p_Email__c = pEmail;
               emailCase.p_Phone__c = pPhone ;
               for(Group g : [SELECT Id FROM Group WHERE name = 'myTeam']){
                    emailCase.OwnerId = g.id;
               }
               try {
                 insert emailCase;
               } catch (System.DmlException e)
                   {System.debug('ERROR: Not able to create Case: ' + e);
                 }
                
              }else if (pEmail == null || pEmail.length() == 0){
                System.debug('No email address was found.');
              }
       // }

        return result;

      } 
      
      
      private String parseEmailContent(String emailText, String dataLabal){
        emailText += '\n';
        String dataValue = '';
        Integer  labalIdx = emailText.indexOf(dataLabal);
        if(labalIdx >= 0){
            dataValue = emailText.substring(labalIdx + dataLabal.length(), emailText.indexOf('\n', labalIdx + dataLabal.length()));
            if(String.isNotBlank(dataValue)){
             dataValue = dataValue.trim();
            }
        }
        return dataValue;
      }
      
      private void sendTestMail(String body ){
          List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
              Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
              List<String> sendTo = new List<String>();
              sendTo.add('riyas.salesforce@gmail.com');
              mail.setToAddresses(sendTo);
              mail.setReplyTo('riyas.salesforce@gmail.com');
              mail.setSenderDisplayName('DebugMail');
              mail.setSubject('Debug Mail');
              mail.setHtmlBody(body);
              mails.add(mail);
          Messaging.sendEmail(mails);
        }
        
} 

    Here I am parsing the email body and the crating the case and accoiating it with contact and account if the email is found in the system.

2. Setup Email Service

Go to Setup => Develop => Email Services => New Email Services ans select your apex class


 Save the changes and click on New Email Address button 


3. Setup Email Service Address

Fill the details and Save 


You get a email address like below



  By sending email to this address creates the case.


Extras 

One major concern is the debugging of apex class. It will not appear in debugg logs. So I have to created a custom apex email function "private void sendTestMail()" to send the details to my Emails.  

NB: This is for my future reference.