1

while calling below code of sendEmail throwing an error as:

First error: SendEmail failed. First exception on row 0; first error: INVALID_FIELD_WHEN_USING_TEMPLATE, When a template is specified the plain text body, html body, subject and charset may not be specified : []

if I remove line - mail.setTemplateId(emailTemp.id); below code works fine. Is there anything wrong I am doing?

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
EmailTemplate emailTemp=[Select Id,Subject, HtmlValue, body from EmailTemplate where name='Notify on oppy closed'];
        List<String> sendTo = new List<String>();
        for(opportunity_contact__c opContact : oppyContact) {
           // sendTo.add(opContact.email__c);
            mail.setSubject(emailTemp.Subject);
            mail.setSenderDisplayName('Test Email');
            mail.setHtmlBody(emailTemp.HtmlValue);
            mail.setPlainTextBody(emailTemp.body);
            mail.setTargetObjectId('0031100000YDHru');
            mail.setSaveAsActivity(false);
            mail.setWhatId(opContact.opportunity__c);
            mail.setTemplateId(emailTemp.id); // #throwing error here
            mails.add(mail);
        }
        Messaging.sendEmail(mails);

Custom Email Template :

Dear {!Opportunity_Contact__c.Name__c}, 
TEXT Here.....
TEXT Here.....
TEXT Here.....TEXT Here.....
Opportunity : {!Opportunity.Id}
Regards,
{!User.FirstName} {!User.LastName} 
{!Organization.Name}

Thanks in advance!

2

Since you are specifying the attribute "mail.setTemplateId(emailTemp.id)", again no need to specify all those attributes. The below link will give you more information

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_single.htm#apex_Messaging_SingleEmailMessage_methods

  • Thanks sunny, but even if i removed all other setter parameter, the error will remain same – Bharat Sep 23 '14 at 10:17
  • Can you post the updated code again. – sunny Sep 23 '14 at 18:09
2

If you remove these two lines

 mail.setHtmlBody(emailTemp.HtmlValue);
 mail.setPlainTextBody(emailTemp.body);

your code should work

0

AFTER this step Messaging.sendEmail(mails);

PUT this: mails.clear();

This works for me.

0
    for(opportunity_contact__c opContact : oppyContact) {
       // sendTo.add(opContact.email__c);
        mail.setTargetObjectId('0031100000YDHru');
        mail.setWhatId(opContact.opportunity__c);
        mail.setTemplateId(emailTemp.id); // #throwing error here
        mails.add(mail);
    }

You cannot modify subject and content when using template to send an email via APEX.

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.