+ Start a Discussion

Send Email with template using API

Hi All,

I've written a code in c# to send an email using API and using template in sales force, but i am unable to access the variables in the template i.e. how would the variables get values in templates by using API.

My template body has following variable {!Opportunity.Account} which contains account name of the opportunity.
And following is my code:

SingleEmailMessage[] messages = new SingleEmailMessage[1];
messages[0] = new SingleEmailMessage();
messages[0].emailPriority = EmailPriority.High;
messages[0].replyTo = "test@salesforce.com";
messages[0].saveAsActivity = false;
messages[0].targetObjectId = "005R0000000HncC";
messages[0].useSignature = true;
messages[0].templateId = "00X40000000nbZ8";
SendEmailResult[] result = binding.sendEmail(messages);

The email is being sent successfully but with no account name. i.e. if the template body is "Opportunities account name is {!Opportunity.Account}" then it is sent as "Opportunities account name is"

Can anyone help me to find out how should i relate the object and object id from code i.e. how to fill the variables which are used in template body.

Help is appreciated.

According to the Apex Reference guide, it says you should use the setWhatIds which is an ID[ ] to further ensure that merge fields are correct.  these can include Contract, Case, Opportunity and Product.  Also, it indicates that if you are using TargetObjectId, you need to set a whatIDs for each one. (page 220, 221 ).
Only emails to contacts can use whatid. But i am sending email to opportunity owner. :(
Didn't know that.  Sorry.

I have a similar requirement where I am using a User rather than a Contact and my email template can not be "passed" the current Opportunity object.


Is there a way to have this work without creating a temporary Contact?  Creating a temp Contact may require to delete it afterward and the problem is that it looks like email are sent asynchronously and I can end up deleting the temp  Contact before the mail is sent out (hence aborting the operation).