December 4, 2019

How to relate Lead to EmailMessage and EmailMessageRelation?

Sample Code:

  1. EmailMessage emailMessage = new EmailMessage();  
  2. emailMessage.status = '3'// email was sent  
  3. emailMessage.fromName = 'Magulan Duraipandian'// from name  
  4. emailMessage.subject = 'This is the Subject!'// email subject  
  5. emailMessage.htmlBody = '<html><body><b>Hello</b></body></html>'// email body  
  6. //Lead Id  
  7. String[] toIds = new String[]{'00Q3i0000018EKHEA2'};   
  8. emailMessage.toIds = toIds;  
  9. // additional recipients who don’t have a corresponding contact, lead or user id in the Salesforce org (optional)  
  10. //emailMessage.toAddress = 'emailnotinsalesforce@toexample.com, anotherone@toexample.com';  
  11. insert emailMessage; // insert  
  12.   
  13. // Add Email Message Relation for id of the sender  
  14. EmailMessageRelation emr = new EmailMessageRelation();  
  15. emr.emailMessageId = emailMessage.Id;  
  16. emr.relationId = '00Q3i0000018EKHEA2'// Lead Id  
  17. emr.relationType = 'FromAddress';  
  18. insert emr;  

2 comments:

  1. I have written EmailMessage and EmailMessageRelation object logic in Batch class as per my requirement, I also wrote Test class for the same but I am getting error on last line in execute method(insert emr) while running the test. Test class is covering the entire class but giving error on last line, can you please share the test class of above code so that I can refer it from here. Thanks in advance.

    ReplyDelete
    Replies
    1. Check why the insert is failing.
      There shouldn't be any issue with the test class.
      https://www.infallibletechie.com/2020/05/test-class-for-emailmessage-and.html

      Delete