I have the following error when trying to send an email.
System.EmailException: SendEmail failed. First exception on row 0; first >error: UNKNOWN_EXCEPTION, List has no rows for assignment to SObject: []
List<User> users = [SELECT Name, Email, Id FROM User WHERE Recipient__c = TRUE and isActive = TRUE];
EmailTemplate et = [SELECT id FROM EmailTemplate WHERE DeveloperName='Advisor'];
for(User u : users) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(u.Id);
mail.setSenderDisplayName('Salesforce');
mail.setUseSignature(false);
mail.setBccSender(false);
mail.setSaveAsActivity(false);
mail.setTemplateId(et.id);
Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}
The list users contains at least one record and the Emailtemplate
is not null.
This is the result of the mail system debug:
(Messaging.SingleEmailMessage[ getBccAddresses=null; getCcAddresses=null; getCharset=null; getEntityAttachments=null; getFileAttachments=null; getHtmlBody=null; getInReplyTo=null; getOptOutPolicy=SEND; getOrgWideEmailAddressId=null; getPlainTextBody=null; getReferences=null; getTargetObjectId=005D0XXXXXXXXXuIAE; getTemplateId=00XD0XXXXXXXXcbMAA; getToAddresses=null; getWhatId=null; isTreatBodiesAsTemplate=false; isTreatTargetObjectAsRecipient=true; isUserMail=true; ])
sendEmail
invocations in a transaction. You should instantiate the list before your loop, add each element to it inside of the loop, and then send the list once when your loop is done. – Adrian Larson♦ May 17 '17 at 16:32User
record whereRecipient__c
is true? – Adrian Larson♦ May 17 '17 at 17:08