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
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 theTask.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
-
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?– cropredyCommented Jun 26, 2020 at 21:44
-
-
-
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