I have a custom object that have a custom email field. I need to send email to the email address which is stored in that email field.
But as I read we cant use setTargetObjectID with custom objects. Is there any workaround this? I have tried creating a lookup relation to contact and then set the contact id and I have set the setToAddresses method of Messaging.SingleEmailMessage to the emailid field from my custom object.
But I get the error: Messaging.SendEmailError[getMessage=The target object's email address "null" is not valid;getStatusCode=INVALID_EMAIL_ADDRESS;
Want to know what values needs to be set here and how can I use setTargetObjectID with a custom object without creating a lookup of the custom field with contact field.
This is the piece of code:
private Messaging.SingleEmailMessage createEmail(EmailTemplate template,
Patient__c patient)
{
try{
//System.debug('email id is: ' + patient.Email_Id__c);
if(patient.Contact__r.id != null) {
List<String> toaddress = new List<String>();
toaddress.add(patient.Email_Id__c);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setTemplateId(template.id);
//System.debug('temalate id: ' + template.id);
email.setTargetObjectId(patient.Contact__r.id);
email.setWhatId(patient.id);
email.setorgWideEmailAddressId(owe.get(0).id);
email.setToAddresses(toaddress);
return email;
}
return null;
}
Appreciate any kind of help here. Thanks a lot.