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
Pranav S SanvatsarkarPranav S Sanvatsarkar 

When does salesforce creates records of EmailMessage object? E.g. Email Alert, Single/Mass Email Message (Apex), Send Email (Standard button on Activities?

Hello there,

I am implementing a custom inbox functionality for community users in my project. I know I can track all outgoing emails from Salesforce using the object EmailMessage. However, I am still not clear in what cases, Salesforce creates EmailMessage records? E.g. Send an Email (standard functionality), Single/Mass Email Message (Apex), etc.

Thanks in advance.
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Pranav,

Please refer the below code for reference.

VisualForce:
<apex:page controller="email_class">
 <apex:form >
  <apex:pageBlock >
   <apex:pageblockButtons >
    <apex:commandButton value="sendEmail" action="{!send}"/>
   </apex:pageblockButtons>
     <b>Enter Subject:</b><apex:inputText value="{!subject}"/>
     <b>Enter Email Body:</b><apex:inputText value="{!email_body}"/>
     
  </apex:pageBlock>
 </apex:form>
</apex:page>

Apex Code:
public with sharing class email_class {
    public string subject{set;get;}
     public string email_body{set;get;}
     List<string> emails = new List<string>{'rahulkumar.b8@gmail.com'};     
public PageReference Send(){
Messaging.singleEmailmessage email = new Messaging.singleEmailmessage();
email.setSubject(subject);
email.setPlainTextBody(email_body);
email.setToAddresses(emails);
Messaging.sendEmail(new Messaging.singleEmailmessage[]{email});
//Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
return null;
}
    public pagereference emailmanager(){   
        return null;
    
}
}

I hope it will be helpful.

Please mark it as best answer if the above information is informative.

BestRegards
RahulKumar
Pranav S SanvatsarkarPranav S Sanvatsarkar
Hello Rahul,

Thanks for the code snippets. However, that is not what I am currently looking out for. 

This is what my observations regarding email messages.
  • Emails sent through Email Alerts or System Emails ( reset password, new user registration) are not logged using EmailMessage object records. This is because these messages are not logged as Acivities associated with related Standard or Custom objects
  • Only those EmailMessage records are created and preserved which are associated to either Standard or Custom Objects using the field Related To. Such EmailMessages need to be logged as they appear in ActivityHistory records related list under detail pages of those object records
Please, let me know if my understandings are incorrect.

Thanks.