0

When sending an email from the lead screen. Is it possible to get the lead id in the before of the EmailMessage trigger?

1 Answer 1

2

For objects other than Lead and Contact

The before trigger on EmailMessage should include a value for RelatedToId which is the parent of the email message (e.g., the Opportunity.Id). Your trigger will need to requery to get values from the Opportunity and do so in a bulkified manner.

Note that EmailMessage.RelatedToId is polymorphic and not every EmailMessage will have an Opportunity as parent. Thus, you'll want code something like

for (EmailMessage em: Trigger.new) {
  if (em.RelatedToId.getSobjectType() == Opportunity.SObjectType) {
      // collect the RelatedToIds in a set to query for Opportunities
  }
}

// bulkified query for Leads and put in map<ID,Opportunity>

// second pass through Trigger.new to deal with EmailMessage for Opportunity

For emails sent from Lead or Contact

  • the beforeInsert trigger has no value for RelatedToId
  • the afterInsert trigger has no value for RelatedToId
  • the afterInsert trigger does have a value for ActivityId that points at a Task and the Task.WhoId points at the Lead (or Contact).

So, you'll need to use an afterInsert trigger, query (bulkified) all parent Task including their WhoId field

Set<Id> taskIds = new Set<Id>();
for (EmailMessage em: Trigger.new) {
  taskIds.add(em.ActivityId);
}

Task[] tasks = SELECT 
    TYPEOF Who
       WHEN Contact THEN Id, Email, FirstName, LastName, Account.Name
       WHEN Lead THEN Id, Company, Email
       ELSE Name
    END
    FROM Task WHERE Id IN: taskIds;

 // do something with the Tasks that reference Leads
8
  • Thanks for the answer. When I send an email from the lead, the EmailMessage.RelatedToId is null in the before of the EmailMessage trigger. So it didn't work. Commented Jun 26, 2020 at 19:55
  • @HenriqueArguto - how are you sending the email from the Lead - via quick action? from the Activity related list? from feed-based layout?
    – cropredy
    Commented Jun 26, 2020 at 21:44
  • Hi, @cropredy. I use a feed-based layout Commented Jun 29, 2020 at 12:42
  • @HenriqueArguto -- updated answer
    – cropredy
    Commented Jun 30, 2020 at 17:47
  • Thanks for the feedback. But the idea was to check the recordType of the lead and change the From. Before sending the email. Commented Jul 2, 2020 at 12:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .