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
BenPBenP 

email attachment loop wrong

I have the code below, but it is incrementing the attachments for each email.  So the first has the correct number, but each one after just keeps adding to that number.  It's like I need to reset that list, but I'm unsure how.

It should accept a list of ids from a flow, then send an email with the record's attachments for each record.
 
@InvocableMethod
    public static void sendEmail(List<String> invoiceID) 
    {
        string emailAddresses;
        
        List<International_Invoice__c> invoices = [SELECT Id, Freight_Forwarder_Email__c FROM International_Invoice__c WHERE Id in :invoiceID];
		List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage> ();  
        List < Messaging.EmailFileAttachment > attachments = new List < Messaging.EmailFileAttachment > ();
        
        List<Id> attIds = new List<Id>();
        for (International_Invoice__c invoice : invoices) {
        emailAddresses =  'ben.p@test.com';
         
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setToAddresses(new String[]{emailAddresses});
        
        message.setSubject('subject');
        message.setHtmlBody('body' );  // If the body is empty, use an empty string
        // Don't set the reply to, because it's auto-calculated.
        message.setUseSignature(true);
        message.setSaveAsActivity(true);
        
            for(Attachment att: [select id,body,parentId,contentType,Name from Attachment where parentId =: invoice.Id])
            {
                Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
                attach.setContentType(att.ContentType);
                attach.setFileName(att.Name);
                attach.setBody(att.body);
                attachments.add(attach);
                attIds.add(att.id);
            }
               
        message.setFileAttachments(attachments);
            
                mails.add(message);
        }
        Messaging.sendEmail(mails);
    }

 
Best Answer chosen by BenP
BenPBenP
Typing this out might have helped.  I added the below to line 36 which seems to have helped.
attachments.clear();
I welcome feedback though.  I'm not an experienced developer in any sense.