I am trying to query emailMessage objects related to a custom object. When I try the query in the Developer console query editor it returns results, also works in workbench. However when I use the same query in an Apex class it gives an error. The query is:

SELECT Id FROM EmailMessage WHERE RelatedToId = :customObject.Id 

And the error is:

No such column 'RelatedToId' on entity 'EmailMessage'.

The same happens with:

SELECT Id, RelatedToId FROM emailMessage

Also, probably related as is referencing the same relationship field, the following query isn't working:

SELECT (SELECT Id FROM Emails) FROM Custom_Object__c 

The background to this is trying to attach a file to the emailMessage, I attach in the apex class and it is sent with email however the emailMessage record doesn't have the attachment, is there an option to attach it, I can't find any, and this would solve my problem although I still can't understand why the above isn't working.

  • 1
    Can you check the version of Apex Class as according to the release doc RelatedToId is a recently added field to EmailMessage object. Check release doc here, releasenotes.docs.salesforce.com/en-us/summer16/release-notes/…
    – Devendra
    Commented Oct 7, 2016 at 13:26
  • Also, you need to enable "Enhanced Email" feature for this.
    – Devendra
    Commented Oct 7, 2016 at 13:33
  • @Devendra Thank you, it is often the simple solution, updating API version fixed it. That said it would be nice for an option to save the attachment to the emailMessage record. Commented Oct 10, 2016 at 12:25
  • I'm glad, it worked for you. EmailMessage has one field "HasAttachment" which checks if this EmailMessage contains any Attachment.
    – Devendra
    Commented Oct 10, 2016 at 13:21

1 Answer 1


You need to enable the Enhanced Email feature in order to use that field in apex.

Also, if you want to relate the email message with a User, Lead or Contact, you need to use the EmailMessageRelation object.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .