Skip to main content

I have the following Apex which is supposed to grab the latest file attached to the opportunity, grab an email template, and send an email to an external email address. The issue I have is that is not attaching the latest file but its attaching the latest attachment of the opportunity. Everything is working fine but I just seem to be stuck with this. Here is the Apex:

global class OpportunityEmailService {

    

    @InvocableMethod(label='Send Email with Latest Attachment' description='Send an email with the latest attachment added to the opportunity to a specific email address.')

    global static void sendEmailWithLatestAttachment(List<Id> opportunityIds) {

        List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>();

        

        // Recipient email address

        String recipientEmail = 'juan.quintero@pennfoster.edu';

        

        // Query for the latest attachment related to each Opportunity

        for(Id oppId : opportunityIds) {

            List<Attachment> latestAttachments = [SELECT Id, Name, Body 

                                                  FROM Attachment 

                                                  WHERE ParentId = :oppId 

                                                  ORDER BY CreatedDate DESC 

                                                  LIMIT 1];

            

            if(!latestAttachments.isEmpty()) {

                Attachment latestAttachment = latestAttachments[0];

                

                // Retrieve Opportunity Owner and Account information

                Opportunity opp = [SELECT OwnerId, Owner.Email, AccountId, Account.Name 

                                   FROM Opportunity 

                                   WHERE Id = :oppId 

                                   LIMIT 1];

                

                if (opp != null && opp.OwnerId != null && opp.Owner.Email != null && opp.AccountId != null && opp.Account.Name != null) {

                    // Create the email message

                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                    

                    // Set the email template ID

                    EmailTemplate emailTemplate = [SELECT Id, Subject FROM EmailTemplate WHERE DeveloperName = 'B2B_Contracts' LIMIT 1];

                    if(emailTemplate != null) {

                        email.setTemplateId(emailTemplate.Id);

                        // Set email subject with merge fields

                        String subjectWithMergeFields = emailTemplate.Subject.replace('{!Account.Name}', opp.Account.Name);

                        email.setSubject(subjectWithMergeFields);

                    } else {

                        System.debug('Email template not found');

                        // Handle the case where the email template is not found

                        continue; // Skip to the next iteration

                    }

                    

                    // Set the recipient email address

                    email.setToAddresses(new String[] {recipientEmail});

                    

                    // Render the email template with merge fields from the opportunity and account

                    String renderedEmailBody = Messaging.renderStoredEmailTemplate(emailTemplate.Id, oppId, null).getHTMLBody();

                    

                    // Set email body

                    email.setHtmlBody(renderedEmailBody);

                    

                    // Set sender as the Opportunity Owner using Organization-Wide Email Address

                    OrgWideEmailAddress[] orgWideEmails = [SELECT Id FROM OrgWideEmailAddress WHERE Address = 'sfapiuser@pennfoster.edu' LIMIT 1];

                    if (orgWideEmails.size() > 0) {

                        email.setOrgWideEmailAddressId(orgWideEmails[0].Id);

                    } else {

                        System.debug('Organization-Wide Email Address not found');

                        // Handle the case where the Organization-Wide Email Address is not found

                        continue; // Skip to the next iteration

                    }

                    

                    // Create email file attachment

                    Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();

                    attachment.setFileName(latestAttachment.Name);

                    attachment.setBody(latestAttachment.Body);

                    email.setFileAttachments(new Messaging.EmailFileAttachment[]{attachment});

                    

                    // Set saveAsActivity flag to false

                    email.setSaveAsActivity(false);

                    

                    emailList.add(email);

                } else {

                    System.debug('Opportunity Owner or Account information not found for Opportunity Id: ' + oppId);

                }

            } else {

                // Handle the case where no attachment is found

                System.debug('No attachment found for Opportunity Id: ' + oppId);

            }

        }

        

        // Send the emails

        if(!emailList.isEmpty()) {

            Messaging.sendEmail(emailList);

        }

    }

}

 

#Salesforce Developer  #Sales Cloud

4 respostas
  1. 11 de abr. de 2024, 23:48

    No comma.  Only space.

     

      @InvocableMethod(label='Send Email with Latest Attachment' description='Send an email with the latest attachment added to the opportunity to a specific email address.')

0/9000