+ Start a Discussion
Roger WickiRoger Wicki 

Send email to asset owners using email template

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
Best Answer chosen by Roger Wicki
Roger WickiRoger Wicki
I just found this and think it solves the problem for everybody
https://salesforce.stackexchange.com/a/144498/10330

All Answers

Manj_SFDCManj_SFDC
Hello Roger,
check if this works 
try using a Visual Force email template:
refer this http://www.forcedisturbances.com/2012/04/automatically-sending-email-reminders.html
Or, you can create a contact for the user on the fly , use that, and then delete the contact .

please mark this as solved if this helps you !
Good luck !
Roger WickiRoger Wicki
Hi Manj

Both options seem more than suboptimal. The first doesn't allow me to set a custom subject relevant to the Asset and the second is plain terrible in performance.
Roger WickiRoger Wicki
I just found this and think it solves the problem for everybody
https://salesforce.stackexchange.com/a/144498/10330
This was selected as the best answer
Manj_SFDCManj_SFDC
Hey Roger, glad that you found the solution, good luck !