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
chikkuchikku 

How send email setToAddresses dynamic based on Contact email id

I need to send a dynamic setToAddresses email id with the contact I choose
public class sendAnEmail
{
    
    @InvocableMethod(label='Test' description='sends an email')
    public static void sendEmailWithAttachment(List<id> listofQuoteHeader)
    {
     List<Contact> Con = [SELECT Id, Email FROM Contact ];
           for(Id QuoteHeaderid :listofQuoteHeader)
           {
               PageReference pref= page.PDFGEN;
               pref.getParameters().put('id',(Id)QuoteHeaderid);
               pref.setRedirect(true);
               
               Attachment attachment = new Attachment();      
               Blob b=pref.getContentAsPDF();
               attachment.Body = b;
               attachment.Name = Datetime.now().format('yyyy-MM-dd HH:mm') + ' ' + 'Quote' + '.pdf';
               attachment.IsPrivate = false;
               attachment.ParentId = QuoteHeaderid;
               insert attachment;
               
               Messaging.SingleEmailMessage semail= new Messaging.SingleEmailMessage();
               Messaging.EmailFileAttachment attach= new Messaging.EmailFileAttachment();
               attach.setBody(pref.getContentAsPDF());
               semail.setSubject('Quote Issued');
       String[] emailIds= new String[]{'abc@gmail.com'}; // I need this part has  dynamic based on contact email id
               semail.setToAddresses(emailIds);
               
               semail.setPlainTextBody('Please find the attached quote details');
               semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
               Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
           }
    }
 
}

 
Best Answer chosen by chikku
ShivankurShivankur (Salesforce Developers) 
Hi Chikku,

You can use code like below in your class to dynamic setToAddresses email id as per the contact provided:
for (Contact myContact : con) {
      //Set list of people who should get the email
      List<String> sendTo = new List<String>();
      sendTo.add(myContact.Email);
      mail.setToAddresses(sendTo);
}
And if you wish to get the related objects contact email id to be selected then can go with below type of code:
String[] emailIds= new String[]{quotesMap.get(QuoteHeaderid)?.Contact.Email};
semail.setToAddresses(emailIds);
You can also write a trigger on your custom object Apple, so when a record is created, above code will fetch the email address of the contact associated with it and add it to the sendToAddresses method.

Hope above information helps, Please mark as Best Answer so that it can help others in the future.

Thanks.