I am receiving the following exception when trying to send an email through Apex:
Exception: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: "[email protected]": [toAddresses, "[email protected]"]
Apex code to send email:
try {
// Create an email invitation for everyone in the contacts list
if (!contacts.isEmpty()) {
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
for (String contact : contacts) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
System.debug('TO ADDRESS: ' + new String[] {contact});
email.setToAddresses(new String[] {contact});
email.setOrgWideEmailAddressId('0D250000000TQTP') ;
email.setSubject('Invitation');
email.setHtmlBody('Please click the link to accept invitation: <a href="' + invitationURL + '">Invitation</a>' );
emails.add(email);
}
// Send the email invitations
List<Messaging.SendEmailResult> sendEmailResults = Messaging.sendEmail(emails);
// Returns feedback message if email was sent successfully or not
for (Messaging.SendEmailResult result : sendEmailResults) {
if (result.IsSuccess()) {
emailSent = true;
System.debug('Email sent successfully!');
} else {
System.debug('There was an error. The email was not sent.');
System.StatusCode statusCode = result.getErrors()[0].getStatusCode();
String errorMsg = result.getErrors()[0].getMessage();
System.debug('Status code: ' + statusCode);
System.debug('Error msg: ' + errorMsg);
}
}
}
} catch (Exception e) {
System.debug('Exception: ' + e);
}
}
Can anyone shine some light on this issue? It will send the email successfully when I hardcode the contact email like so email.setToAddresses(new String[] {'[email protected]'})
but not when I dynamically set the address.
EDIT:
public void sendInvitations() {
// Send out email invites to all contacts on list
if (emailAddresses != null) {
sendHigiInvite.sendEmail(emailAddresses, UserInfo.getSessionId());
}
}
contacts
gets passed to this email method as a parameter List<String>
. I check if it is null before passing it to the method. My log shows this as the value for contacts
10:22:03:007 USER_DEBUG [28]|DEBUG|CONTACTS: ("[email protected]", "[email protected]")
contacts
? Are you sure it does not contain anynull
values?"[email protected]"
instead of just[email protected]
?