Salesforce Email To Case using Inbound Email Service with Assignment Rule

Salesforce Email To Case using Inbound Email Service with Assignment Rule

assignmentRuleHeader.useDefaultRule should be set to true using Database.DMLOptions to trigger Assignment Rule when the Case is created 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 {
        
            EmailMessage emailMessage = new EmailMessage();
            Case objCase = new Case ( Description = myPlainText, Subject = email.Subject );
            Database.DMLOptions dmlOpts = new Database.DMLOptions();
            dmlOpts.assignmentRuleHeader.useDefaultRule = true;
            
            if ( email.toAddresses.size() > 0 ) {
            
                emailMessage.ToAddress = String.join( email.toAddresses, ';' );
                objCase.Email_Service__c = email.toAddresses.get( 0 );
                
            }
            
            objCase.Origin = 'Email';
            objCase.Status = 'New';
            objCase.setOptions( dmlOpts );
            insert objCase;      
             
            emailMessage.Status = '0'; // email is New
            emailMessage.FromAddress = email.FromAddress;
            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:

Leave a Reply