function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Marx Prathap Singh ShanmugamMarx Prathap Singh Shanmugam 

Hi all, using apex i need to insert custom data to an EmailMessage object.the record need to assigned to a contact's Activity. how to achieve this??

Here is my code
Contact cts= new Contact();
cts.Id=[SELECT Id FROM Contact Where Email='contact@email.com'].Id;
System.debug('Contact id'+cts.Id);
EmailMessage emailMsg = new EmailMessage(); // Created a EmailMessage and copy all details from above.
emailMsg.FromAddress='fromaddress@email.com';
emailMsg.ToAddress='toaddress@email.com';
emailMsg.Subject='Email using Apex';
emailMsg.RelatedToId=cts.Id;
emailMsg.HtmlBody='Temp Email using apex code';
emailMsg.ParentId = null; //Attach with the case
emailMsg.MessageDate = system.now();
emailMsg.Status = '0';
insert emailMsg;
Venkata Naresh Thatha 8Venkata Naresh Thatha 8
Here is corrected code... Let me know if you it works out for you...


public class Insert_Email {
    public insert_email() {
Id id2=[SELECT Id FROM Contact Where Email='tvnaresh@gmail.com'].id;
System.debug('Contact id'+id2);
EmailMessage emailMsg = new EmailMessage(); // Created a EmailMessage and copy all details from above.
emailMsg.FromAddress='abc@yahoo.com';
emailMsg.ToAddress='abc@gmail.com';
emailMsg.Subject='Email using Apex';
emailMsg.RelatedToId='0060I00000UEA4KQAX';// related to opportunity
emailMsg.HtmlBody='Temp Email using apex code';
emailMsg.ParentId = null; //Attach with the case
emailMsg.MessageDate = system.now();
emailMsg.Status = '0';
insert emailMsg;
}}
Marx Prathap Singh ShanmugamMarx Prathap Singh Shanmugam
Hi Venkata Naresh,
It is showing the below error.
User-added image
I have just modified the emailm from address,to address and the relatedtoID
and my code is,

public class Insert_Email {
public insert_email() {
Id id2=[SELECT Id FROM Contact Where Email='marxprathap_ava@hotmail.com'].id;
System.debug('Contact id'+id2);
EmailMessage emailMsg = new EmailMessage(); // Created a EmailMessage and copy all details from above.
emailMsg.FromAddress='marxprathap_ava@hotmail.com';
emailMsg.ToAddress='Marx@AvaPrathap.onmicrosoft.com';
emailMsg.Subject='Email using Apex';
emailMsg.RelatedToId='0037F00000PmptPQAR';// related to opportunity
emailMsg.HtmlBody='Temp Email using apex code';
emailMsg.ParentId = null; //Attach with the case
emailMsg.MessageDate = system.now();
emailMsg.Status = '0';
insert emailMsg;
}
}
Venkata Naresh Thatha 8Venkata Naresh Thatha 8
Hi , i just created a new object.  Try running " insert_email  e = new insert_email()" in anonymous window.   Also, please note that the code is not that perfect, you need to work more to add on the features.

User-added imageUser-added image