You need to sign in to do that
Don't have an account?
Cristian_Cocioban
Body is empty when sending email to a user from apex with Visulaforce email template
I want to send emails from apex, I'm using Visualforce email templates. This is my code:
Email template:
It's sending the email but the body is empty.
When sending from setup and using "Send Test and Verify Merge Fields" - it works - body is sent.
I've tried this: Sending Emails in Salesforce to Non-Contacts Using Apex . It throws an error a null reference error, I've checked in the log and the emailBody is null.
I've tried setting email.setWhatId(usr.Id); - no change
The only solution that worked was building the message as string in apex and using email.setHtmlBody(someString);
However I'm curious of why using the template doesn't work, any help would be highly appreciated.
EmailTemplate templateId = [Select id from EmailTemplate where DeveloperName = 'User_Template']; OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress LIMIT 1]; for(User usr: users) { Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); if ( owea.size() > 0 ) { email.setOrgWideEmailAddressId(owea.get(0).Id); } email.setSaveAsActivity(false); email.setSubject('Test Subject'); email.setTargetObjectId(usr.Id); email.setTemplateID(templateId.Id); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email }); }
Email template:
<messaging:emailTemplate subject="Test" recipientType="User"> <messaging:htmlEmailBody > this is a test </messaging:htmlEmailBody> </messaging:emailTemplate>
It's sending the email but the body is empty.
When sending from setup and using "Send Test and Verify Merge Fields" - it works - body is sent.
I've tried this: Sending Emails in Salesforce to Non-Contacts Using Apex . It throws an error a null reference error, I've checked in the log and the emailBody is null.
I've tried setting email.setWhatId(usr.Id); - no change
The only solution that worked was building the message as string in apex and using email.setHtmlBody(someString);
However I'm curious of why using the template doesn't work, any help would be highly appreciated.
You need to query all fields in email template and assign those fields to messageing class like below.
Hope this helps you!
Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com
All Answers
if you are using setOrgWideEmailAddressId then Query in an OrgWideEmailAddress object and follow my code it is working for me
please let me know if this was helpful
thank you
Avaneesh Singh
You need to query all fields in email template and assign those fields to messageing class like below.
Hope this helps you!
Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com