0

We've set up a Apex REST endpoint to send emails on behalf of an external system.

Data to fill the templates will be sent in the JSON payload to the REST endpoint.

We're finding that the data is going to be diverse and changing and like to simply pass the data from the JSON payload into the email template without storing it on an object first.

I see that we can set a WhatId and a TargetObjectId when using the Messaging.SingleEmailMessage object, but it doesn't seem to support ephemeral fields.

Is it possible to send a templated email in Apex without storing the data first?

1 Answer 1

1

In SFDC, email templates draw on their merge fields from three basic places:

  • The recipient (targetObjectId) in the Apex SingleEmailMessage. In VF this is {!Recipient.xxx} and in normal email templates, this is any reference to {!Contact.xxx} or {!Lead.xxx} or {!User.xxx}.
  • The related to record (whatId) in the Apex SingleEmailMessage. In VF this is {!RelatedTo.xxx} and in normal email templates, this is any reference to someObject.xxx (e.g. Account, Case, order, CustomObj__c`
  • The runtime environment - things like the running user {!$User.xxx}

So, if you want to avoid storing the JSON data in an object first ...

An Option

Your Apex needs to construct the message body manually using String methods. You can exploit System.Messaging.renderEmailTemplate (see doc) , take the result using getMergedBody() and then insert using String methods your dynamic text from the JSON

2
  • 1
    To add, the substitution can be done before the render call to allow you to make it look like the standard {!...} format, where you search and replace these types of value from the unsaved record, or you can use your own delimiters. Note that you lose the power of expressions in this approach. An alternative is to add a save point, insert the record(s), render the email bodies, into in memory strings, roll back to the save point then send the emails.
    – Phil W
    Commented Mar 23, 2022 at 6:59
  • @PhilW thank you. I had forgotten about the savepoint-rollback trick
    – cropredy
    Commented Mar 23, 2022 at 14:35

You must log in to answer this question.

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