I have a custom object that allows my users to create series of emails to their clients. I have a scheduled Apex job running hourly that scans for emails that are schedule to go out, creates the EmailMessages and sends them out. I have fields for recipient lists and options to use the Contact as Target Object id.
This setup has been working for 5 years, and suddenly stopped working for emails that have a target object id, but no additional recipents. Has something changed in the new release?
Here's how I set up the Email Message:
public static Messaging.SingleEmailMessage createMessage(Email__c e){
List<String> recipients = e.Email_List__c.split(',');
Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
msg.setUseSignature(False);
msg.setTemplateId((Id)e.Email_Template_ID__c);
msg.setSaveAsActivity(true);
if(!recipients.isEmpty()) msg.setToAddresses(recipients);
if(e.Send_to_Contact__c){
msg.setTargetObjectId(e.Contact__c);
msg.setWhatId(e.Trip__c);
}
else{
msg.setTargetObjectId(e.TargetObjectForEmail__c);
System.debug('target object id:'+e.TargetObjectForEmail__c);
}
if(e.From_Triggering_User__c == True){
msg.setOrgWideEmailAddressId(ScheduleEmails.CurrentUserOWA);
}
else if(e.OrgWideEmail__c != ''){
msg.setOrgWideEmailAddressId((Id)e.OrgWideEmail__c);
}
System.debug('adding message. The target object id is:'+msg.getTargetObjectId());
return msg;
}
And here's how I send them:
List<Messaging.SendEmailResult> results = Messaging.sendEmail(emailsToSend, false);
Integer numResults = results.size();
String errorMessage;
System.StatusCode statusCode;
//loop through results
for(Integer i = 0; i < numResults; i++){
//get the result and email object
Messaging.SendEmailResult r = results.get(i);
Email__c e = preparedEmails.get(i);
if (r.isSuccess()) {
e.Sent_Date__c = datetime.now();
sentEmails.add(e);
}
else{
statusCode = r.getErrors()[0].getStatusCode();
errorMessage = '';
for(Messaging.SendEmailError error:r.getErrors()){
errorMessage += error .getMessage() + '\r\n';
}
errorMessageReport += '\r\n' + errorMessage + '\r\nLink: ' +
System.Url.getSalesforceBaseURL().toExternalForm() + '/' + e.id
+ '\r\nThe recipient list: ' + e.Email_List__c;
}
}
The error is:
Invalid to address :
I have triple checked that the contacts have valid email addresses.
Does anyone know what could be the issue?