Reputation: 1225
Im trying to send an email in Apex with the SingleEmailMessage() function using an existing Template and connecting it with a custom object record.
mail = new Messaging.SingleEmailMessage();
mail.setTemplateId('00Xb0000000iwks');
mail.setTargetObjectId(a.CAccount__r.OwnerId); //lookup on account
mail.setToAddresses(new List<String>{a.CAccount__r.Owner.Email}); //email from account owner
mail.setTreatTargetObjectAsRecipient(false);
mail.setSaveAsActivity(false);
mail.setWhatId(a.Id);
this.mails.add(mail);
Here i want to fill the template data with the custom object record "a". But i get the following error:
WhatId is not available for sending emails to UserIds.
Nowhere could i find an explicit answer that an Email in Apex can only be sent with a contact object in setTargetObjectId(). What i want to refrain from doing is to temporarily create a contact for the sole purpose of sending an email !?
Thanks in advance if someone has an idea
Upvotes: 1
Views: 9111
Reputation: 1225
i found at last the following solution taken from : http://opfocus.com/sending-emails-in-salesforce-to-non-contacts-using-apex/
// Pick a dummy Contact
Contact c = [select id, Email from Contact where email <> null limit 1];
// Construct the list of emails we want to send
List<Messaging.SingleEmailMessage> lstMsgs = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
msg.setTemplateId( [select id from EmailTemplate where DeveloperName='My_Email_Template'].id );
msg.setWhatId( [select id from Account limit 1].id );
msg.setTargetObjectId(c.id);
msg.setToAddresses(new List<String>{'[email protected]'});
lstMsgs.add(msg);
// Send the emails in a transaction, then roll it back
Savepoint sp = Database.setSavepoint();
Messaging.sendEmail(lstMsgs);
Database.rollback(sp);
// For each SingleEmailMessage that was just populated by the sendEmail() method, copy its
// contents to a new SingleEmailMessage. Then send those new messages.
List<Messaging.SingleEmailMessage> lstMsgsToSend = new List<Messaging.SingleEmailMessage>();
for (Messaging.SingleEmailMessage email : lstMsgs) {
Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
emailToSend.setToAddresses(email.getToAddresses());
emailToSend.setPlainTextBody(email.getPlainTextBody());
emailToSend.setHTMLBody(email.getHTMLBody());
emailToSend.setSubject(email.getSubject());
lstMsgsToSend.add(emailToSend);
}
Messaging.sendEmail(lstMsgsToSend);
It actually works fine - with only the difference that i created a dummy contact of my own instead of using an existing one - because there might be none available or accidentally send out an email to the selected dummy - so better use the following:
Contact dummyContact = new Contact();
dummyContact.LastName = 'DummmyContact';
dummyContact.Email = '[email protected]';
Upvotes: 1