May 7, 2021

Salesforce Email To Case using Inbound Email Service

Sample Apex Class:

global class createCaseInbound implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail( Messaging.InboundEmail email, Messaging.InboundEnvelope env ) {
   
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();         
        String myPlainText = email.plainTextBody;
           
        try {
        
            Case objCase = new Case ( Description = myPlainText, Subject = email.Subject );
            objCase.Origin = 'Email';
            objCase.Status = 'New';
            insert objCase;      
            
            EmailMessage emailMessage = new EmailMessage();  
            emailMessage.Status = '0'; // email is New
            emailMessage.FromAddress = email.FromAddress;
            if ( email.toAddresses.size() > 0 )
                emailMessage.ToAddress = String.join( email.toAddresses, ';' );
            if ( email.ccAddresses != null && email.ccAddresses.size() > 0 )
                emailMessage.CcAddress = String.join( email.ccAddresses, ';' );
            emailMessage.FromName = email.FromName; // from name  
            emailMessage.Subject = email.Subject; // email subject  
            emailMessage.TextBody = myPlainText; // email body  
            emailMessage.RelatedToId = objCase.Id;
            insert emailMessage; // insert    
                
            result.success = true;       
            
        } catch ( Exception e ) {
        
            System.debug( 'Error is: ' + e.getMessage() );   
            result.success = false;     
            
        }        
        return result;
        
    }
    
}

Email Service:
 
 
Output:


2 comments:

  1. This is very helpful, but a couple things:

    The EmailMessage also has an EmailMessageRelation object. I'm not sure how that works here, or if it is automatically created when the ToAddress and CcAddress is populated.

    Additionally, there is ToIds and CcIds which are relational to User/Contact/Lead records. I think it's generally preferable to populate the email message with those Ids, but it also makes it much trickier with a custom handler. Salesforce's native Email2Case functionality already does this, and trying to re-code for it is a bit frustrating.

    ReplyDelete
    Replies
    1. EmailMessageRelation will link the record to the email message.https://www.infallibletechie.com/2019/12/how-to-relate-lead-to-emailmessage-and.html

      Delete