Sample Code:
Apex Class:
public class EmailMessageHandler {
public static void insertEM( String recordId ) {
EmailMessage emailMessage = new EmailMessage();
emailMessage.status = '3'; // email was sent
emailMessage.fromName = 'Test Name'; // from name
emailMessage.subject = 'This is the Subject!'; // email subject
emailMessage.htmlBody = '<html><body><b>Hello</b></body></html>'; // email body
//Lead Id
String[] toIds = new String[]{ recordId };
emailMessage.toIds = toIds;
// additional recipients who don’t have a corresponding contact, lead or user id in the Salesforce org (optional)
//emailMessage.toAddress = '[email protected], [email protected]';
insert emailMessage; // insert
// Add Email Message Relation for id of the sender
EmailMessageRelation emr = new EmailMessageRelation();
emr.emailMessageId = emailMessage.Id;
emr.relationId = recordId;
emr.relationType = 'FromAddress';
insert emr;
}
}
Test Class:
@isTest
public class EmailMessageHandlerTest {
@isTest
public static void testEM() {
Lead objLead = new Lead( LastName = 'Test', Company = 'Example', Email = '[email protected]' );
insert objLead;
Test.startTest();
EmailMessageHandler.insertEM( objLead.Id );
Test.stopTest();
}
}