Here is the code-
public static void sendEmailToUser(String email, String emailTemplateNameText, String selectedRecordId){
String emailTemplateName = '%' + emailTemplateNameText + '%';
String emailForQuery = '%' + email + '%';
system.debug('selectedRecordId: '+selectedRecordId);
EmailTemplate emailTemplate = [SELECT Name, DeveloperName, Id, Body
FROM EmailTemplate
WHERE Name like :emailTemplateName
AND IsActive = true
LIMIT 1];
Contact dummyContact = [SELECT Id, Name, Email
FROM Contact
WHERE Name <> null
AND Email <> null
limit 1];
User userRec = [SELECT Id, name, Username, email
FROM User
where Email like :emailForQuery
limit 1];
OrgWideEmailAddress owa = [SELECT id, DisplayName, Address
FROM OrgWideEmailAddress
limit 1];
System.debug('EmailTemplate: '+emailTemplate.Id);
System.debug('email: '+email);
System.debug('dummyContact.Id: '+dummyContact.Id);
System.debug('selectedRecordId: '+selectedRecordId);
String templateId = emailTemplate.Id;
String userId = userRec.Id;
String whatId = selectedRecordId;
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setTemplateId(emailTemplate.id);
email.setTargetObjectId(dummyContact.Id);
email.setWhatId(selectedRecordId);
email.saveAsActivity = false;
List<string> toAddress = new List<string>();
toAddress.add(email);
email.setToAddresses(toAddress);
if(!Test.isRunningTest()) {
try {
Messaging.SendEmailResult[] sendEmailResult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
for(Messaging.SendEmailResult r : sendEmailResult){
if (r.success) {
System.debug('Successfully sent email to '+toAddress[0]);
}else{
System.debug('The email failed to send: ' + r.errors[0].message);
}
}
} catch (Exception e) {
System.debug(e.getMessage());
}
}
}
The debug logs for this method reflect that the System debugs all have the correct values. The merge fields are also populating correctly, and the debug log at the success also executes. However the email isn't sent and I get the above exception. I'm using a custom email template for this example, if that might be an issue.
setTargetObjectId
is the recipient by default). Whatever index out of bounds error you're getting is in the code calling this code.