Skip to main content
Dear community

I need to send an email to owners of assets when certain criteria are met. I have a custom child object to the asset, called an asset reminder, which stores information about what kind of reminder (email template), what date and what interval the notification should be sent. I use scheduled apex to send these emails every night.

This is my code:

/**

* Prepares an email per reminder

*/

@TestVisible private void prepareNofifications() {

for ( AssetReminder__c reminder : assetReminders ) {

transient Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

message.setTemplateId(reminder.EmailTemplateId__c);

message.setTargetObjectId(assets.get(reminder.AssetId__c).OwnerId); // assets is of type map<Id, Asset>

message.setWhatId(reminder.AssetId__c);

message.setSaveAsActivity(false);

emails.add(message);

}

}

However I receive an error when it executes:

Reminder Dispatcher could not send out reminders.

Exception Type: System.EmailException

Exception Cause: null

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

Reading up on that error shows that if I specify a WhatId, I can not use a UserId for the TargetObjectId. On one hand this is a total no brainer and on the other hand my template uses asset and user merge fields. What am I supposed to do? I can not simply replace that stuff with a contact.

Does anybody have a workaround for this?

Best

Roger
4 respuestas
0/9000