0

I'm getting this exception where trying to send email:

SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, SaveAsActivity is not allowed with whatId that is not supported as a task whatId.: [whatId, 00301000002mirW]

I know it wil work if I will set the saveActivity to false, but I want it to be true.

WhatId in my case is ContactId, as can be seen in the script below.

Any idea what is the issue?

Contact con = [select Id,Email from Contact where Id = '00301000002mirW'];
                
Messaging.SingleEmailMessage mail = Messaging.renderStoredEmailTemplate('00X01000000LyOQ', null, con.Id);
mail.setTargetObjectId(con.Id);
mail.setToAddresses(new list<String>{con.Email});
mail.setReplyTo(con.Email);
mail.setBccSender(false);
mail.setUseSignature(false);
mail.saveAsActivity = true; 
                    
Messaging.sendEmail( new list<Messaging.SingleEmailMessage>{mail});

1 Answer 1

2

Rendering the template with the contact Id sets the target object to the contact already, so calling it again tries to associate it to an object. There's no need to render the template, as it will be rendered when sent.

Also, don't set the to address of the contact, as the address is automatically sent to from the target object record. Doing this will result in the subject receiving multiple copies of the email.

Additionally, setting the setReplyTo to the contact's email will effectively disable the ability to reply to the email, as their mail client will then reply to themselves.

The renderStoredEmailTemplate is typically only used to create a preview of the email without actually sending it. You shouldn't make any further modifications to the mail after rendering (except for the various flags and additional email addresses).

This is all your code needs to do:

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId('00X01000000LyOQ');
mail.setTargetObjectId(con.Id);
mail.saveAsActivity = true; 
                    
Messaging.sendEmail( new list<Messaging.SingleEmailMessage>{mail});
1
  • Thanks. I previoulsy wanted to use both the target object and the related to, as I was using the {!RelatedTo.Id} in the template, I changed it to be {!Recipient.Id} and now indeed it is enough to set only the target object. The contact email in the script was only for testing, in the real code it is optional email with sales user email.
    – Liron C
    Commented Dec 9, 2020 at 15:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .