Salesforce Order Creation using Inbound Email Service

Salesforce Order Creation using Inbound Email Service

To Setup Inbound Email Service, check the following link

Sample Apex Class:

Apex Class:

global class OrderCreation implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail( Messaging.InboundEmail email, Messaging.InboundEnvelope env ) {
   
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();         
        String myPlainText= '';               
        myPlainText = email.plainTextBody;
        System.debug( 'myPlainText value is ' + myPlainText  );
        List < String > strList = new List < String >();
           
        try {
        
            if ( myPlainText.contains( 'Order Creation Template Start' ) ) {
                
                Order objOrder = new Order();
                strList = myPlainText.split( '\n' );
                String accountNumber;
                
                for ( String str : strList ) {
                
                    System.debug( 'String Value is ' + str );
                    
                    if ( str == 'Order Creation Template End' ) {
                        
                        break;
                        
                    } else if ( str.contains( 'Account Number' ) ) {
                    
                        accountNumber = str.substringAfter( ': ' );
                    
                    } else if ( str.contains( 'Start Date' ) ) {
                    
                        objOrder.EffectiveDate = Date.valueOf( str.substringAfter( ': ' ) );
                    
                    }
                
                }
                
                List < Account > listAccounts = [ SELECT Id FROM Account WHERE AccountNumber =: accountNumber ];
                
                if ( listAccounts.size() > 0 ) {
                
                    objOrder.AccountId = listAccounts.get( 0 ).Id;
                    objOrder.Status = 'Draft';
                    insert objOrder;  
                
                }
            
            }             
            
        }
           
        catch ( Exception e) {
        
            System.debug( 'Error is: ' + e.getMessage() );
            
        }  
         
        result.success = true;        
        return result;
        
    }
    
}

Sample email:

Output:

Leave a Reply