0

I am using Salesforce email service to create records on a custom case object when an email is received. I have the following apex class that handles the incoming emails. It is working fine for majority of email addresses and it create records but it fails for few email addresses and I receive the error msg.

Apex class:

public class className implements Messaging.InboundEmailHandler {

    public Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                                                           Messaging.InboundEnvelope envelope) 
    {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();   
        Custom_object__c ttCase = new Custom_object__c();

        if(email.references == null){
            ttCase = createTTCase(email);
        } else {
            List<Custom_object__c> ttCaseList = getExistingRecord(email);
            ttCase = ttCaseList[0];
        }
        
        if (ttCase.Id != null) {
            createTTEmailMessage(ttCase.Id, email);
        }
            
        if(email.textAttachments != null && ttCase.Id != null) {
            createTextAttachment(ttCase.Id, email);
        }
        
        if(email.binaryAttachments != null && ttCase.Id != null){
            createBinaryAttachment(ttCase.Id, email);
        }
       
        return result;
   }
    
    @testVisible  
    private static Custom_object__c createTTCase(Messaging.InboundEmail inboundMessage){

        Custom_object__c tt = new Custom_object__c();
        
        try {
            tt.Requestor_Email__c = inboundMessage.fromAddress;
            tt.Requestor_Name__c = inboundMessage.fromName;
            tt.description__c = inboundMessage.htmlBody;
            tt.Opened__c = Datetime.now();
            tt.Subject__c = String.isNotBlank(inboundMessage.subject) ? inboundMessage.subject : 'No Subject';
     
            insert tt;
            
        } catch(Exception e) {
            System.debug('The following exception has occurred on createTTCase : ' + e.getMessage());
        }
        
        return tt;
   }
    
    
    @testVisible
    private static void createTextAttachment(String parentRecordId, Messaging.InboundEmail emailMessage){
        List<Attachment> textAttachemntList = new List<Attachment>();
        
        try {
            for (Messaging.Inboundemail.TextAttachment tAttachment : emailMessage.textAttachments) {
                Attachment attachment = new Attachment();
                attachment.Name = tAttachment.fileName;
                attachment.Body = Blob.valueOf(tAttachment.body);
                attachment.ParentId = parentRecordId;
                textAttachemntList.add(attachment);
            }
            
            if(textAttachemntList.size()>0){
                insert textAttachemntList;
            }
        } catch (Exception e) {
            system.debug('Exception occurred on createTextAttachment : ' + e.getMessage());
        }
    }
    
    @testVisible
    private static void createBinaryAttachment(String parentRecordId, Messaging.InboundEmail emailMessage) {
        List<Attachment> binaryAttachment = new List<Attachment>();
        try {
            for (Messaging.Inboundemail.BinaryAttachment bAttachment : emailMessage.binaryAttachments) {
                Attachment attachment = new Attachment();
                attachment.Name = bAttachment.fileName;
                attachment.Body = bAttachment.body;
                attachment.ParentId = parentRecordId;
                binaryAttachment.add(attachment);
            }
        
            if(binaryAttachment.size()>0){
                insert binaryAttachment;
            }
        } catch (Exception e) {
            system.debug('Exception occurred on createBinaryAttachment : ' + e.getMessage());
        }
    }
   
    @testVisible
    private static void createTTEmailMessage(String ttCaseId, Messaging.InboundEmail email) {

        EmailMessage em = new EmailMessage();
        try {

            em.HtmlBody = email.htmlBody;
            em.TextBody = email.plainTextBody;
            em.Incoming = true;
            em.Status = '1';
            em.ToAddress = (email.ToAddresses == null || email.ToAddresses.isEmpty()) ? '' : String.join(email.ToAddresses, ',');
            em.FromAddress = email.fromAddress;
            em.FromName = email.fromName;
            em.RelatedToId = ttCaseId;
            em.CcAddress = (email.ccAddresses == null || email.ccAddresses.isEmpty()) ? '' : String.join(email.ccAddresses, ',');
            em.Subject = String.isNotBlank(email.subject) ? email.Subject : 'No Subject';
        
            insert em;
                    
        } catch (Exception e) {
            system.debug('Exception occurred on createTTEmailMessage : ' + e.getMessage());
        }
   }
    
    @testVisible
    private static List<Custom_object__c> getExistingRecord(Messaging.InboundEmail email) {
        
        List<Custom_object__c> ttCase = new List<Custom_object__c>();
        List<String> referenceId = email.references;
        List<EmailMessage> prevmail = [SELECT RelatedToId from EmailMessage WHERE ThreadIdentifier =: referenceId LIMIT 1];
        if(prevmail.size() > 0){
            ttCase = [SELECT Id FROM Custom_object__c WHERE Id=: prevmail[0].RelatedToId];            
        }
        if(ttCase.isEmpty() || prevmail.isEmpty())
        {
            Custom_object__c ttCaseObj = createTTCase(email);
            ttCase.add(ttCaseObj);
        }
        
        return ttCase;
    }
    
    
}

Error msg:

The apex class CaseEmailService failed due to: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent]

---------------

    The attached email could not be processed because the Apex class CaseEmailService failed.
    
    System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent]
    
    Class.CaseEmailService.createBinaryAttachment: line 87, column 1
    Class.CaseEmailService.handleInboundEmail: line 25, column 1

This is line 25: createBinaryAttachment(ttCase.Id, email);

This is line 87: insert binaryAttachment;

1
  • It seems like the try-catch in createBinaryAttachment is not handling the exception as it should, but the logic is correct apparently. If you are using Vs Code, can you confirm the logic in the class "className" in Salesforce has the code as in your local project? Have you identified a patron in the emails that fail? May 29, 2023 at 23:54

0

You must log in to answer this question.