0

I have an Email Service with an Apex class that creates a new EmailMessage object associating the sender with a Contact in the system and the recipient as a User. The email shows up correctly with all the fields populated but without the "Reply" buttons. When I create an email from a User to a User the buttons are visible.

I am also creating an EmailMessageRelation as per the EmailMessage docs, and setting the ToIds field on the EmailMessage which is supposed to automatically associate it with the recipient (User) as described in the following docs snippet:

enter image description here

According to the above I should have the "Reply" functionality but for some reason I am not getting it. Any insight would be appreciated.

0

After a lot of trial and error I got it to work by adding two separate EmailMessageRelation objects; one for the sender (in my case a Contact) with the RelationType set to "FromAddress" and an additional one for the recipient (in my case a User) with the RelationType set to "ToAddress". Apparently the documentation for EmailMessage is not precise since adding the ToAddress and ToIds fields set to the User did not automatically associate the recipient with the User and in fact I removed those fields and it works fine.

Here is the relevant working code:

EmailMessage newEmail = new EmailMessage();
    newEmail.Status = '2'; //sent
    newEmail.Subject = email.subject;
    newEmail.TextBody = textBody;
    newEmail.HtmlBody = htmlBody;
    newEmail.RelatedToId = recordId;
    newEmail.Incoming = true;

Contact senderContact = ContactRepository.getContactByEmail(jsonObject.get('sender email'));

    if (senderContact != null) {
        Id messageId = AddSenderToMessage(senderContact, newEmail);
        AddEmailRelationship(messageId, senderContact.Id, 'FromAddress');
        AddEmailRelationship(messageId, recipient.Id, 'ToAddress');

        result.success = true;
        return result;
    }

private Id AddSenderToMessage(Contact contact, EmailMessage newEmail) {
    newEmail.FromName = contact.Name;
    newEmail.FromAddress = contact.Email;
    insert newEmail;
    return newEmail.Id;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.