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
MaggieSumitMaggieSumit 

I create apex class for sending email template with attachment. When I uploading data through data loader then I am getting the issue.

Like I am updating a single record than its sending a specific attachment for that contact record, but when I updating data by data loader it's attaching all attachment from all contacts and sending on email. 

please help me on this,

thanks
public with sharing class OpportunityMatchingHelper {
 
    public static List<alu_Opportunity_Matching__c> sendEmail(List<alu_Opportunity_Matching__c> oppList) { 
        Map<Id,alu_Opportunity_Matching__c> OppMapByIDs = new Map<Id,alu_Opportunity_Matching__c>();
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        
        EmailTemplate et=[Select Id,Subject,HtmlValue,Body FROM EmailTemplate WHERE Name=:'Pitched'];          
        for(alu_Opportunity_Matching__c opMap : oppList){
            if(opMap.Application_Status__c == 'Pitched'){
                OppMapByIDs.put(opMap.Applicant_Student_Record__c, opMap);    
            }        
        }
        for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :OppMapByIDs.keySet()])
        {
           Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
           efa.setFileName(a.Name);
           efa.setBody(a.Body);
           fileAttachments.add(efa);
        }
        
        for(alu_Opportunity_Matching__c opp :OppMapByIDs.values()){           
            if(opp.Applicant_Student_Record__c != null){
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
                singleMail.setTargetObjectId(opp.Applicant_Student_Record__c);
                singleMail.setTemplateId(et.Id);
                singleMail.setWhatId(opp.Id);
                singleMail.setSaveAsActivity(false);
                singleMail.setReplyTo('mycareer@alueducation.com');
                   singleMail.setSenderDisplayName('ALU Career Development');
                singleMail.setFileAttachments(fileAttachments);
                emails.add(singleMail); 
            }
        }  
        Messaging.sendEmail(emails);
        return null;
    }
}
 
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Sumit,

May I suggest you please refer the below link for reference. Hope it will be helpful.

Please mark it as best answer if the information is informative.

Thanks
Rahul Kumar