Skip to main content

How to associate EmailMessage with Lead record using apex?

I am creating a new EmailMessage record from my apex code and I want that this record should be associated to a Lead record. As per documentation, we can not use RelatedToId

RelatedToId : The RelatedToId represents nonhuman objects such as accounts, opportunities, campaigns, cases, or custom objects. RelatedToIds are polymorphic. Polymorphic means a RelatedToId is equivalent to the ID of a related object.

and if I try to use it , I get a

FIELD_INTEGRITY_EXCEPTION : Invalid id type

Is there any way we can associate EmailMessage to Lead?

The larger picture about what I have to do here is that:

We are sending an single email message from a lightning component button click through apex SingleMessage. When we do this, a record of activity history should be created for this lead and I have to add some custom fields on this activity history record to show some more information. I used setWhatId and setSaveAsActivity(true) methods of Messaging.SingleEmailMessage class but that gives a similar error as RelatedToId:

SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, SaveAsActivity is not allowed with whatId that is not supported as a task whatId.: [whatId, 00Q3a00000pHXf4]

Sarang
  • 2.7k
  • 8
  • 55
  • 102