[SalesForce] Is it possible to access the email of a Lead’s owner directly

For instance, I am writing some code to send an email using a after insert trigger. I am wanting to get the email address of the lead owner I am currently iterating over, but am running into an error.

public static void sendAdrEmailNotification(List<Lead> leadList) {

     ...

     for (Lead lead : leadList) {
          ...
          singleMail.setToAddresses(lead.Owner.Email); //Email cannot be resolved
          ...
     }
}

How can I get the email address of the lead owner in the Apex code? I know I can use a SOQL query but I obviously do not want to do this in a for loop so I'm not sure where to go from here.

Best Answer

You don't need soql to do that, you can directly use setTargetObjectId

setTargetObjectId(targetObjectId)

optional . The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.Required if using a template,

so your code will be

for (Lead lead : leadList) {
          ...
           if(lead.OwnerId.getSobjectType() ==  User.SObjectType)
          singleMail.setTargetObjectId(lead.OwnerId); 
          ...
     }

The advantage of using setTargetObjectId is, you can send unlimited emails to the user. If manually specify email id then you are restricted to only 5000 emails a day limit.

src: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm

Related Topic