There are many posts about creating Case threadIds with Apex, notably Case.Thread_Id, is Thread_Id a field on Case object?

As the posters have noted, the SFDC rules of the threadId are subject to change over time and the only reliable way that I've seen is to do this:

// To be replaced with a real case Id.
Id caseId = '500c0000008kJL5'; 

List<Messaging.RenderEmailTemplateBodyResult> renderResults =
  Messaging.renderEmailTemplate(null, caseId, new List<String>{'{!Case.Thread_Id}'});

System.debug('this is the Case Thread Id: ' + renderResults[0].getMergedBody());

HOWEVER ... The method call Messaging.renderEmailTemplate burns a SOQL (see doc)

So you can't prepopulate your Cases in an afterInsert or beforeUpdate Trigger because a transaction can be up to 2,000 (Platform Events), up to 10,000 (direct Apex DML) or more, typically, 200 rows. All of these are > 100 SOQL limit.

So, before I go to the trouble of doing this in a chained set of async tasks; is there more recent thinking on this subject of creating ThreadIds?


For now, if you need this, you'll have to go asynchronous. Queueable would probably be best, but that's up to your discretion. There's an idea to enable a field that could be used, and presumably that could solve the problem at a more fundamental level, so you might want to vote on it.

  • yes -- a difficult issue as one wants the threadId for use in VF email templates based on deltas in Case; so PBs and WFR need to be gated by presence of threadId before executing and async Txn, even with soql limit of 200 can't consume all 200 doing renderEmailTemplate as that leaves no headroom for soqls done by the aforementioned WFR/PBs. Tuning for the right "batch size" in the async txn is "guessing/leaving enough headroom and hoping for the best". Your remark if you need this... is spot-on
    – cropredy
    Oct 25 '18 at 1:43

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.