I have an Apex class that runs every ten minutes and sends emails for some opportunities that were created in the system. Or at least, that is how it should work, but I'm getting an INVALID_FIELD_WHEN_USING_TEMPLATE
exception when sending them, even though I don't specify the fields that Salesforce says that are invalid.
The exception says the following:
When a template is specified, the plain text body, html body, subject, charset, and "treatBodiesAsTemplate" may not be specified
But I don't specify none of those in my code. I even put the email message in a debug line so I could see the parameters, and I get the following (formatted for better visualization):
Messaging.SingleEmailMessage[
getBccAddresses=(<my email addresses>);
getCcAddresses=null;
getCharset=null;
getDocumentAttachments=null;
getFileAttachments=null;
getHtmlBody=null;
getInReplyTo=null;
getOrgWideEmailAddressId=0D211000000CbbrCAC;
getPlainTextBody=null;
getReferences=null;
getTargetObjectId=00311000017I5y0AAC;
getTemplateId=00X11000000EDMOEA4;
getToAddresses=null;
getWhatId=0061100000C2ztMAAR;
isUserMail=false;
]
To clarify: I am using an email template for this, that "accepts" two Ids: an Opportunity Id and a Contact Id.
This is really frustrating. What can it be?
The code I'm using can be found at https://gist.github.com/renatoliveira/3795fce852f08260361e but I've changed some strings for anonymity.
The template is somewhat as follows (also redacted):
<messaging:emailTemplate subject="{!relatedTo.custom_field_b__c}"
recipientType="Contact"
relatedToType="Opportunity"
replyTo="{!relatedTo.custom_field__r.Email}">
<messaging:htmlEmailBody >
<div class="maindiv" style="font-family: Arial, sans">
Hello {!recipient.Salutation} {!recipient.FirstName},<br/><br/>
[REDACTED]
<br/><br/>You may get in touch with him/her <b><a href="mailto:{!relatedTo.custom_field__r.Email}">{!relatedTo.custom_field__r.Email}</a></b> or by phone (<b>[REDACTED]</b>).
<br/><br/>Thank you for the opportunity and always count on us and on our support.
<br/><br/>If you need further information, do not hesitate to contact us.
<br/><br/>Best regards,<br/><br/>
<b>[REDACTED]</b>
</div>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
TargetObjectId
with any address fields, despite what the message says.