+ Start a Discussion
EyalEyal 

Catching email exception while getting the email

Hi Friends, 

 

I am sending an email based on template. I want to count the number of times emails are count successfully.

 

As you can see here:

 

 

try {
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
     Messaging.SendEmailResult[] mailResult = Messaging.sendEmail(new      
Messaging.SingleEmailMessage[] { mail }); if ( !mailResult[0].isSuccess() )
{ EmailFailure = 'Email Failed: ' + mailResult[0].getErrors()[0].getMessage() +' \n \n'; } else { EmailCounter.Emails_sent_from_apex__c = EmailCounter.Emails_sent_from_apex__c +
Number_Of_Recipients ; update EmailCounter; } } catch(System.EmailException emlEx)
{ EmailFailure = 'we got here: ' + emlEx+' \n \n'; }

The surprising thing is that I do get the email as expected BUT an  Email exception is till thrown. As a result my counter is not updated, even though an email was sent. 

 

The Email exception received is:  System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_FIELD_WHEN_USING_TEMPLATE, When a template is specified the plain text body, html body, subject and charset may not be specified : []

 

Just to make is clear - I am NOT using :text body, html body, subject and charset.

 

Why do I get this exception ?

 

Please Help :)

 

Eyal

 

Best Answer chosen by Admin (Salesforce Developers) 
Alex.AcostaAlex.Acosta

This sounds like an issue you are having with one of the email params you are setting up... can you please post those?

 

I recently had to write a wizard to send emails again and mine looks like such:

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

...

// Set our params 
mail.setTargetObjectId(lead.Id);
mail.setWhatId(customSobjectRecord.Id);
mail.setToAddresses(new String[] {'test@test.com'});
mail.setSenderDisplayName(this.account.Name);
mail.setSaveAsActivity(false);
mail.setTemplateId(emailTemplate.Id);

try{            
     Messaging.SendEmailResult[] resultMail = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

if(resultMail[0].isSuccess()){ // email sent successfully
// code to do stuff goes here.... } else{ response = resultMail[0].getErrors().get(0).getMessage(); } }catch(System.EmailException ex){ response = ex.getMessage(); }