function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Tyler HarrisTyler Harris 

Struggling With Attachments in Messaging.InboundEmailHandler{}

Hi All,

I'm getting a null exception error on line 27 when I look for email.binaryAttachments.size(). I'm attaching files to my emails before I send them, but they're not attaching to the Lead.

Apex
global class EmailDemoReceive implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInBoundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){
        
       Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        if([select count() from Lead where Name = :email.subject]==0){
         
            Lead leadz = new Lead();
            String addy = email.subject;
           
            if(String.isNotEmpty(addy)){
             List<String> nameParts = addy.split('\\bCompany=\\b');
            String namePart = addy.remove('Company=');
            System.debug(namePart);
            system.debug(nameParts);
 
            leadz.LastName = email.fromName;
            leadz.Company = namePart;
            String chopit = leadz.company;
            system.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;    
           
             insert leadz;   
          
                system.debug(email.binaryAttachments);
         
                    for(Integer i = 0; i < email.binaryAttachments.size(); i++){
                        Attachment attach = new attachment();
                        attach.ParentId = leadz.id;
                        attach.Name = email.binaryAttachments[i].filename;
                        attach.Body = email.binaryAttachments[i].body;
                        System.debug(attach);
                        
                        insert attach;
                        system.debug(attach.Id);
                    } 
                
                
            }
            
            else{
            leadz.LastName = email.fromName;
            System.debug(leadz.Company);
            leadz.Company = 'Unknown';
            System.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;
            insert leadz;   
                
            }
          
            
        }

        return result;
        
    }

}

 
Best Answer chosen by Tyler Harris
Vivek DeshmaneVivek Deshmane
have u commented Insert emailmessage statement? IF not Please comment and try to send txt attachment.

All Answers

Vivek DeshmaneVivek Deshmane
Hi Tyler,
Please use below code and let me know if it works.
global class EmailDemoReceive implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInBoundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){
        
       Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        if([select count() from Lead where Name = :email.subject]==0){
         
            Lead leadz = new Lead();
            String addy = email.subject;
           
            if(String.isNotEmpty(addy)){
             List<String> nameParts = addy.split('\\bCompany=\\b');
            String namePart = addy.remove('Company=');
            System.debug(namePart);
            system.debug(nameParts);
 
            leadz.LastName = email.fromName;
            leadz.Company = namePart;
            String chopit = leadz.company;
            system.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;    
           
             insert leadz;   
          
                system.debug(email.binaryAttachments);
                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) 
                {
                    for(Integer i = 0; i < email.binaryAttachments.size(); i++){
                        Attachment attach = new attachment();
                        attach.ParentId = leadz.id;
                        attach.Name = email.binaryAttachments[i].filename;
                        attach.Body = email.binaryAttachments[i].body;
                        System.debug(attach);
                        
                        insert attach;
                        system.debug(attach.Id);
                    } 
                }else if (email.textAttachments != null && email.textAttachments.size() > 0)
                {
                    for (integer i = 0 ; i < email.textAttachments.size() ; i++) 
                    {       
                    Attachment txtAttachment = new Attachment();
                    txtAttachment.Name = email.textAttachments[i].filename;
                    txtAttachment.Body = Blob.valueOf(email.textAttachments[i].Body);
                    txtAttachment.ParentId = emailMessage.id;
                    insert txtAttachment;
                
                }
            } 
                
            }
            
            else{
            leadz.LastName = email.fromName;
            System.debug(leadz.Company);
            leadz.Company = 'Unknown';
            System.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;
            insert leadz;   
                
            }
          
            
        }

        return result;
        
    }

}
Best Regards,
-Vivek
Tyler HarrisTyler Harris
Thank you! However, my attachment is not appearing in the Notes & Attachment's section.
Vivek DeshmaneVivek Deshmane
Hi Tyler,
Please check attachment, under email message and let me know if it works.
Best Regards,
-Vivek
Tyler HarrisTyler Harris
Where should this appear? It's not showing.
User-added image
Vivek DeshmaneVivek Deshmane
Hi,
Please Try below code and let me know.
global class EmailDemoReceive implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInBoundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){
        
       Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        if([select count() from Lead where Name = :email.subject]==0){
         
            Lead leadz = new Lead();
            String addy = email.subject;
           
            if(String.isNotEmpty(addy)){
             List<String> nameParts = addy.split('\\bCompany=\\b');
            String namePart = addy.remove('Company=');
            System.debug(namePart);
            system.debug(nameParts);
 
            leadz.LastName = email.fromName;
            leadz.Company = namePart;
            String chopit = leadz.company;
            system.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;    
           
             insert leadz;   
          
        emailMessage.FromName = email.fromName;
        emailMessage.Subject = email.Subject;
        if(email.htmlBody != null){
            if(email.htmlBody.length()>32000){ 
                emailMessage.htmlBody = email.htmlBody.substring(0,21999);}
            else{
                emailMessage.HtmlBody = email.htmlBody;
            }
        }
        if(email.plainTextBody != null){
            if(email.plainTextBody.length()>32000){
                emailMessage.TextBody = email.plainTextBody.substring(0,21999);}
            else{
                emailMessage.TextBody = email.plainTextBody;}
        }
        emailMessage.Incoming = true;
        emailMessage.ParentId = leadz.id;
        emailMessage.FromAddress = email.fromAddress;
                system.debug(email.binaryAttachments);
                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) 
                {
                    for(Integer i = 0; i < email.binaryAttachments.size(); i++){
                        Attachment attach = new attachment();
                        attach.ParentId = leadz.id;
                        attach.Name = email.binaryAttachments[i].filename;
                        attach.Body = email.binaryAttachments[i].body;
                        System.debug(attach);
                        
                        insert attach;
                        system.debug(attach.Id);
                    } 
                }else if (email.textAttachments != null && email.textAttachments.size() > 0)
                {
                    for (integer i = 0 ; i < email.textAttachments.size() ; i++) 
                    {       
                    Attachment txtAttachment = new Attachment();
                    txtAttachment.Name = email.textAttachments[i].filename;
                    txtAttachment.Body = Blob.valueOf(email.textAttachments[i].Body);
                    txtAttachment.ParentId = emailMessage.id;
                    insert txtAttachment;
                
                }
            } 
                
            }
            
            else{
            leadz.LastName = email.fromName;
            System.debug(leadz.Company);
            leadz.Company = 'Unknown';
            System.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;
            insert leadz;   
                
            }
          
            
        }

        return result;
        
    }

}
Best Regards,
-Vivek
Tyler HarrisTyler Harris
Still no attachment.
User-added image
Vivek DeshmaneVivek Deshmane
Forgot insert emailMessage, try it now.

global class EmailDemoReceive implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInBoundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){
        
       Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        if([select count() from Lead where Name = :email.subject]==0){
         
            Lead leadz = new Lead();
            String addy = email.subject;
           
            if(String.isNotEmpty(addy)){
             List<String> nameParts = addy.split('\\bCompany=\\b');
            String namePart = addy.remove('Company=');
            System.debug(namePart);
            system.debug(nameParts);
 
            leadz.LastName = email.fromName;
            leadz.Company = namePart;
            String chopit = leadz.company;
            system.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;    
           
             insert leadz;   
          
        emailMessage.FromName = email.fromName;
        emailMessage.Subject = email.Subject;
        if(email.htmlBody != null){
            if(email.htmlBody.length()>32000){ 
                emailMessage.htmlBody = email.htmlBody.substring(0,21999);}
            else{
                emailMessage.HtmlBody = email.htmlBody;
            }
        }
        if(email.plainTextBody != null){
            if(email.plainTextBody.length()>32000){
                emailMessage.TextBody = email.plainTextBody.substring(0,21999);}
            else{
                emailMessage.TextBody = email.plainTextBody;}
        }
        emailMessage.Incoming = true;
        emailMessage.ParentId = leadz.id;
        emailMessage.FromAddress = email.fromAddress;
        insert emailMessage;
                system.debug(email.binaryAttachments);
                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) 
                {
                    for(Integer i = 0; i < email.binaryAttachments.size(); i++){
                        Attachment attach = new attachment();
                        attach.ParentId = leadz.id;
                        attach.Name = email.binaryAttachments[i].filename;
                        attach.Body = email.binaryAttachments[i].body;
                        System.debug(attach);
                        
                        insert attach;
                        system.debug(attach.Id);
                    } 
                }else if (email.textAttachments != null && email.textAttachments.size() > 0)
                {
                    for (integer i = 0 ; i < email.textAttachments.size() ; i++) 
                    {       
                    Attachment txtAttachment = new Attachment();
                    txtAttachment.Name = email.textAttachments[i].filename;
                    txtAttachment.Body = Blob.valueOf(email.textAttachments[i].Body);
                    txtAttachment.ParentId = emailMessage.id;
                    insert txtAttachment;
                
                }
            } 
                
            }
            
            else{
            leadz.LastName = email.fromName;
            System.debug(leadz.Company);
            leadz.Company = 'Unknown';
            System.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;
            insert leadz;   
                
            }
          
            
        }

        return result;
        
    }

}
Best Regards,
-Vivek
Tyler HarrisTyler Harris
It's throwing a Variable does not exist: emailMessage on line 43.
Vivek DeshmaneVivek Deshmane
Try this.
global class EmailDemoReceive implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInBoundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){
        
       Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        if([select count() from Lead where Name = :email.subject]==0){
         
            Lead leadz = new Lead();
            String addy = email.subject;
           
            if(String.isNotEmpty(addy)){
             List<String> nameParts = addy.split('\\bCompany=\\b');
            String namePart = addy.remove('Company=');
            System.debug(namePart);
            system.debug(nameParts);
 
            leadz.LastName = email.fromName;
            leadz.Company = namePart;
            String chopit = leadz.company;
            system.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;    
           
             insert leadz;   
         EmailMessage emailMessage = new EmailMessage(); 
        emailMessage.FromName = email.fromName;
        emailMessage.Subject = email.Subject;
        if(email.htmlBody != null){
            if(email.htmlBody.length()>32000){ 
                emailMessage.htmlBody = email.htmlBody.substring(0,21999);}
            else{
                emailMessage.HtmlBody = email.htmlBody;
            }
        }
        if(email.plainTextBody != null){
            if(email.plainTextBody.length()>32000){
                emailMessage.TextBody = email.plainTextBody.substring(0,21999);}
            else{
                emailMessage.TextBody = email.plainTextBody;}
        }
        emailMessage.Incoming = true;
        emailMessage.ParentId = leadz.id;
        emailMessage.FromAddress = email.fromAddress;
        insert emailMessage;
                system.debug(email.binaryAttachments);
                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) 
                {
                    for(Integer i = 0; i < email.binaryAttachments.size(); i++){
                        Attachment attach = new attachment();
                        attach.ParentId = leadz.id;
                        attach.Name = email.binaryAttachments[i].filename;
                        attach.Body = email.binaryAttachments[i].body;
                        System.debug(attach);
                        
                        insert attach;
                        system.debug(attach.Id);
                    } 
                }else if (email.textAttachments != null && email.textAttachments.size() > 0)
                {
                    for (integer i = 0 ; i < email.textAttachments.size() ; i++) 
                    {       
                    Attachment txtAttachment = new Attachment();
                    txtAttachment.Name = email.textAttachments[i].filename;
                    txtAttachment.Body = Blob.valueOf(email.textAttachments[i].Body);
                    txtAttachment.ParentId = emailMessage.id;
                    insert txtAttachment;
                
                }
            } 
                
            }
            
            else{
            leadz.LastName = email.fromName;
            System.debug(leadz.Company);
            leadz.Company = 'Unknown';
            System.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;
            insert leadz;   
                
            }
          
            
        }

        return result;
        
    }

}
Best Regards,
-Vivek
Tyler HarrisTyler Harris
Hi Vivek,

Getting an error:

 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Case ID: id value of incorrect type: 00QF000000uQelHMAS: [ParentId]

So is it not possible to attach an email message to a lead?
Vivek DeshmaneVivek Deshmane
Yes,It won't attach to Lead.
Howevre you try to send eamil with text attachment then it will attachment to lead but it will not work for binary attachment.
global class EmailDemoReceive implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInBoundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){
        
       Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        if([select count() from Lead where Name = :email.subject]==0){
         
            Lead leadz = new Lead();
            String addy = email.subject;
           
            if(String.isNotEmpty(addy)){
             List<String> nameParts = addy.split('\\bCompany=\\b');
            String namePart = addy.remove('Company=');
            System.debug(namePart);
            system.debug(nameParts);
 
            leadz.LastName = email.fromName;
            leadz.Company = namePart;
            String chopit = leadz.company;
            system.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;    
           
             insert leadz;   
         EmailMessage emailMessage = new EmailMessage(); 
        emailMessage.FromName = email.fromName;
        emailMessage.Subject = email.Subject;
        if(email.htmlBody != null){
            if(email.htmlBody.length()>32000){ 
                emailMessage.htmlBody = email.htmlBody.substring(0,21999);}
            else{
                emailMessage.HtmlBody = email.htmlBody;
            }
        }
        if(email.plainTextBody != null){
            if(email.plainTextBody.length()>32000){
                emailMessage.TextBody = email.plainTextBody.substring(0,21999);}
            else{
                emailMessage.TextBody = email.plainTextBody;}
        }
        emailMessage.Incoming = true;
        emailMessage.ParentId = leadz.id;
        emailMessage.FromAddress = email.fromAddress;
        //insert emailMessage;
                system.debug(email.binaryAttachments);
                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) 
                {
                    for(Integer i = 0; i < email.binaryAttachments.size(); i++){
                        Attachment attach = new attachment();
                        attach.ParentId = leadz.id;
                        attach.Name = email.binaryAttachments[i].filename;
                        attach.Body = email.binaryAttachments[i].body;
                        System.debug(attach);
                        
                        insert attach;
                        system.debug(attach.Id);
                    } 
                }else if (email.textAttachments != null && email.textAttachments.size() > 0)
                {
                    for (integer i = 0 ; i < email.textAttachments.size() ; i++) 
                    {       
                    Attachment txtAttachment = new Attachment();
                    txtAttachment.Name = email.textAttachments[i].filename;
                    txtAttachment.Body = Blob.valueOf(email.textAttachments[i].Body);
                    txtAttachment.ParentId = emailMessage.id;
                    insert txtAttachment;
                
                }
            } 
                
            }
            
            else{
            leadz.LastName = email.fromName;
            System.debug(leadz.Company);
            leadz.Company = 'Unknown';
            System.debug(leadz.Company);
            leadz.Email = email.fromAddress;
            leadz.Description = email.htmlBody;
            insert leadz;   
                
            }
          
            
        }

        return result;
        
    }

}
Best Regards,
-Vivek
Tyler HarrisTyler Harris
I tried sending with a Txt file and it did not attach either and threw the error:

16:58:31:135 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Case ID: id value of incorrect type: 00QF000000uQf2sMAC: [ParentId]
Vivek DeshmaneVivek Deshmane
have u commented Insert emailmessage statement? IF not Please comment and try to send txt attachment.
This was selected as the best answer