带有模板的 Salesforce Apex SingleEmailMessage 不联系用户

Salesforce Apex SingleEmailMessage with Template to User not contact

我正在尝试使用现有模板在 Apex 中使用 SingleEmailMessage() 函数发送电子邮件,并将其与自定义对象记录连接。

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);    

这里我想用自定义对象记录填充模板数据"a"。但是我收到以下错误:

WhatId is not available for sending emails to UserIds.

我在任何地方都找不到明确的答案,即 Apex 中的电子邮件只能与 setTargetObjectId() 中的联系人对象一起发送。我想避免做的是临时创建一个仅用于发送电子邮件的联系人!?

如果有人有想法,请提前致谢

我终于找到了以下解决方案,取自: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>{'random_address@opfocus.com'});

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);

它实际上工作正常 - 唯一的区别是我创建了我自己的虚拟联系人而不是使用现有的 - 因为可能 none 可用或不小心向选定的虚拟联系人发送了一封电子邮件- 所以最好使用以下内容:

Contact dummyContact = new Contact();
dummyContact.LastName = 'DummmyContact';
dummyContact.Email = 'dummmycontact@dummmycontact.com';