[SalesForce] SendEmail failed. REQUIRED_FIELD_MISSING, Missing targetObjectId with template:

Can any one help me out with this error .

1)When im using mail.setTargetObjectId(c.CustomerSignedId); the system start throwing a error .

SendEmail failed. First exception on row 0; first error:
REQUIRED_FIELD_MISSING, Missing targetObjectId with template:

2)When im using mail.setTargetObjectId('00538000004bjrA'); the system start throwing a error .

SendEmail failed. First exception on row 0; first error:
INVALID_ID_FIELD, WhatId is not available for sending emails to
UserIds.: [whatId, 8004B000000Qmzi]

3)When i use mail.setTargetObjectId(c.OwnerId); ,

i get the email but the merge fields value are not getting displayed

Here is the Code which im using the Batch Class :

global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
                ccAddresses.add(c.Account.Owner.Email);
               // toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setCcAddresses(CcAddresses);
                mail.setTargetObjectId(c.CustomerSignedId);
                //mail.setTargetObjectId('00538000004bjrA');
                mail.setWhatId(c.Id);
                mail.setTemplateId('00X4B000000M3go');
                mail.setSaveAsActivity(false);
           mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }

Any Suggestion very much appreciated.

Best Answer

I see several things happening here.

First, there's an issue with the following:

setCcAddresses(ccAddresses)

Optional. A list of carbon copy (CC) addresses. The maximum allowed is 25. This argument is allowed only when a template is NOT used.

As you're using a template, this obviously causing an issue for you.

Next, it sounds as though you want your email to be about your customer contact, in which case, the contact needs to be the Id you use for:

 `setTargetObjectId(targetObjectId)` 

Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.

You'll note that the above can't be anything other than a one of those three.

For your purposes, you may need to also use this field setting it to false:

setTreatTargetObjectAsRecipient(treatAsRecipient)

Optional. If set to true, the targetObjectId (a contact, lead, or user) is the recipient of the email. If set to false, the targetObjectId is supplied as the WhoId field for template rendering but isn’t a recipient of the email. The default is true.

setWhatId(whatId)

If you specify a contact for the targetObjectId field, you can specify an optional whatId as well. This helps to further ensure that merge fields in the template contain the correct data.

Since you had wanted to reference c.CustomerSignedId, it sounds as though you really want to reference some kind of contract or document that's been signed, if so, that's probably what needs to go here for the WhatId.

The value for the WhatId must be one of the following types:

  • Account
  • Asset
  • Campaign
  • Case
  • Contract
  • Opportunity
  • Order
  • Product
  • Solution
  • Custom

If you want to include yourself as the admin, instead of adding yourself to the cc's or BCC's, you can always just add yourself to the list of email address your sending the email to. However, with a template, you can't do it using any of the below:

setToAddresses(toAddresses)
setCcAddresses(ccAddresses)
setBccAddresses(ccAddresses)

Optional. A list of email addresses to which you are sending the email. The maximum number of email addresses allowed is 100. This argument is allowed only when a template is NOT used.

Instead, using a template, if you want to use set for the addresses, you're going to need to use either an HTML or text email body tag:

setHtmlBody(htmlBody)

Optional. The HTML version of the email, specified by the sender. The value is encoded according to the specification associated with the organization. You must specify a value for setTemplateId, setHtmlBody, or setPlainTextBody. Or, you can define both setHtmlBody and setPlainTextBody. setTreatBodiesAsTemplate(treatAsTemplate)

After doing the above, I suggest you try using this tag if you have merge fields you want to use. It's possible it may work for you without throwing an error. I've not tested it to see, but it's worth a try.

setTreatBodiesAsTemplate(treatAsTemplate)

Optional. If set to true, the subject, plain text, and HTML text bodies of the email are treated as template data.

For more on all the above, see SingleEmailMessage Methods