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
Maf_007Maf_007 

How to Match the Subject With record field and save the attachment with the record

Hi Guys, I have an email server which receives email and compare the email subject with an external id field and if they both match the attachment should be saved against that record I have written the following class but can't figure out how to match and save the attachment. Any help would be appreciated:

 

InboundMessage Class:

 

global class EmailDemoReceive implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                                                         Messaging.Inboundenvelope envelope) {
  	
    //retrieve all eco survey where it matches with the email subject.... 
    List<EcoSurvey__c> existingsurveys = [select id, Job_Reference__c from EcoSurvey__c where Job_Reference__c = :email.subject];
    Map<id,EcoSurvey__c> ES = new Map<id,EcoSurvey__c>{};
        
        for(EcoSurvey__c MES: existingsurveys){
        	ES.put(MES.id, MES);
        }
    try{
        //check Eco Survey for an existing record with same reference and there's an attachment
        if(existingsurveys.size() > 0 && 
           (email.binaryAttachments != null && email.binaryAttachments.size() > 0||
           email.TextAttachment != null && email.TextAttachment.size() > 0)){
            // Save attachments
			for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
  				Attachment attachment = new Attachment();
 
  				attachment.Name = tAttachment.fileName;
  				attachment.Body = Blob.valueOf(tAttachment.body);
  				attachment.ParentId = ES.get(email.subject).id;;
  				insert attachment;
			}
			for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
  				Attachment attachment = new Attachment();
 
  				attachment.Name = bAttachment.fileName;
  				attachment.Body = bAttachment.body;
  				attachment.ParentId = ES.get(email.subject).id;
  				insert attachment;
			}
        }
    
    }Catch(QueryException e){
    
    }
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    return result;
    }
}