Apex发送邮件模板时合并字段值不显示问题求助
Hey there! Let's work through why your merge fields aren't populating correctly when sending emails via Apex—this is a super common issue, so we'll break down the most likely fixes step by step.
Common Causes & Fixes
Double-check your template data associations
Email templates rely on two key IDs to resolve merge fields:setTargetObjectId(): For user/contact/lead records (handles recipient-related fields like{!Contact.Name})setWhatId(): For related records (like Opportunity, Account, or custom objects—resolves fields like{!Opportunity.Amount})
Make sure you've set both (if applicable) in yourMessaging.SingleEmailMessageinstance. For example, if your template uses Opportunity fields, you must includemail.setWhatId(oppRecord.Id);alongside the target contact ID.
Ensure all required fields are loaded in Apex
If you're fetching records via SOQL, you must include every merge field used in the template in your query. For instance, if your template uses{!Opportunity.Name}and{!Opportunity.CloseDate}, your SOQL should look like:Opportunity opp = [SELECT Id, Name, CloseDate FROM Opportunity WHERE Id = :oppId];Don't just query the
Id—Apex won't auto-load other fields, so merge fields will show up empty.Verify template type matches your data
If your template is tied to a Contact object, you can't pass an Account ID as the target object. Double-check that your template's associated object matches thesetTargetObjectId/setWhatIdrecord types. Also, scan your template for typos in merge field syntax (like{!Opportuity.Name}instead of{!Opportunity.Name}—small mistakes break everything!).Pre-render the template to test
Use theMessaging.renderStoredEmailTemplate()method to preview how your template renders before sending. This helps you isolate if the issue is with the template itself or the email sending logic. Here's a quick example:Id templateId = '00Xxxxxxxxxx'; // Your template ID Id targetContactId = '003xxxxxxxxx'; // Recipient contact ID Id whatId = '006xxxxxxxxx'; // Related opportunity ID String renderedContent = Messaging.renderStoredEmailTemplate(templateId, targetContactId, whatId); System.debug('Rendered Template: ' + renderedContent);Check the debug logs to see if merge fields are populated correctly here—if not, the issue is in your data/template setup, not the send step.
Rule out permission issues
The user context running your Apex code needs read access to the target record and all fields used in the merge fields. If the code runs as a user without these permissions, merge fields will be blank. Test usingSystem.runAs()with an admin user to see if permissions are the culprit:System.runAs(new User(Id='005xxxxxxxxx')) { // Admin user ID // Your email sending code here }
If none of these fix the problem, sharing a snippet of your template's merge fields and the specific parts of your Apex code where you set targetObjectId/whatId would help narrow things down further!
内容的提问来源于stack exchange,提问作者Lavi__c

