[SalesForce] Email not being send if whatID is set and setSaveAsActivity is true

I have the following code

if (this.templateId != null)  {
           // parameters specific for visualforce template
               singleEmailMessage.setTargetObjectId(this.targetObjectId);
               //singleEmailMessage.setSaveAsActivity(true);
               singleEmailMessage.setSaveAsActivity(false); 
               singleEmailMessage.setWhatId(this.whatId);
               singleEmailMessage.setTemplateId(this.templateId);
           } else {
               singleEmailMessage.setHtmlBody(this.htmlBody);               
               singleEmailMessage.setPlainTextBody(this.plainTextBody);
               singleEmailMessage.setSubject(this.subject);
           }
return this; 
       }

The message body has a link and if I set the whatID and setSaveAsActivity(true); the email is not being sent.

If I remove the whatID the setSaveAsActivity(true); then the email doesn't send the proper link.

I am very new to apex coding and any help will be appreciated

Best Answer

From the Apex Code Developer's Guide:

setSaveAsActivity(saveAsActivity)

The default value is true, meaning the email is saved as an activity. This argument only applies if the recipient list is based on targetObjectId or targetObjectIds. If HTML email tracking is enabled for the organization, you will be able to track open rates.

The above method relies on you using setTargetObjectIds, to set the WhoID(s) for your email message. If you set the targetobjectIds as anything other than contacts or leads, then you'll have a problem because it creates a Task that's assigned on that Contact or Lead that can also be related to a WhatId.

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.

Usage:

The value must be one of the following types:

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