December 19, 2020

How to populate SourceId in Case in InboundEmailHandler Email Service in Salesforce?

Sample Code:

global class createCaseInbound implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope env) {
  
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();        
        String myPlainText= '';             
        myPlainText = email.plainTextBody;       
                 
        try {
           
            Case objCase = new Case();
            objCase.Subject = email.subject;
            objCase.Origin = 'Email';
            objCase.Status = 'New';
            insert objCase;
                       
            EmailMessage objEmailMessage = new EmailMessage();
            objEmailMessage.ToAddress =  String.join( email.toAddresses, ',' );
            objEmailMessage.FromAddress = email.FromAddress;
            objEmailMessage.FromName = email.FromName;
            objEmailMessage.Subject = email.subject;
            objEmailMessage.status = '2';
            objEmailMessage.HtmlBody = email.htmlBody;
            objEmailMessage.Incoming= true;
            objEmailMessage.TextBody = email.plainTextBody;
            objEmailMessage.RelatedToId = objCase.Id;
            insert objEmailMessage;
                       
            objCase.SourceId = objEmailMessage.Id;
            update objCase;
           
           
        } catch ( Exception e ) {
            System.debug( 'Error is: ' + e.getMessage() );
        } 
        
        result.success = true;       
        return result;
       
    }
   
}

Output:


No comments:

Post a Comment