function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Salesforce seekarSalesforce seekar 

Simple Code Fix needed in EMail body of Send Email Fuctionality...

Hi Team , 
There is some mistake in my string ErrorRecord storing error details,its coming incorrect while sending an email.

Scenario : let us suppose say i have 3 contact records to insert out of which 1 contact giving correct AccountId and rest 2 i am putting an accountId which doesnot exists , it will be calculated as error or failure records. 
now i want to send those 2 record details with name in a single email to user saying that these are the names of the records that got failed..... 

Issue: while sending 2 error record details email to user , i am getting the mail output like below for two failure records.

Please find the list of failure records(insufficient access rights on cross-reference id: 0012v00003Tg5Qd  for RecordName: Error insufficient access rights on cross-reference id: 0012v00003Tg6Qd  for RecordName: green
)  --->first record details are missing

Expected: Would need body like error records like below or any other way to clearly notify users.

Dear User , 
Please find the list of below failure records.
insufficient access rights on cross-reference id: 0012v00003Tg5Qd  for RecordName: Red , 
insufficient access rights on cross-reference id: 0012v00003Tg5Qd  for RecordName: green
=============================
code: 
public with sharing class ContactCreationController {
 @AuraEnabled
public static contWrapper createDuctProductRecords(contWrapper contRecords){
         System.debug('===Methodcalled==='+contRecords);  
    
        list<Contact> Conlist = (List<Contact>)JSON.deserialize(contRecords.records, List<Contact>.Class);
      List<String> ErrorList = new List<String>();
        String ErrorRecord= '';  
 //Insert operation      
     List<Database.saveResult> result = Database.insert(Conlist,false);
        for (integer i=0; i < result.size(); i++) 
         {
            if(result.get(i).isSuccess()) {
                    contRecords.successCount++;
                   }
             else if(! result.get(i).isSuccess()){ 
                contRecords.ErrorCount++;
              
                Database.Error dbError = result.get(i).getErrors().get(0);   
                ErrorRecord += dbError.getMessage()+ ' '+' '+'for RecordName: '+(String)Conlist[i].get('Name')+'\n';  
            }
         } 
             ErrorList.add(ErrorRecord);    
            system.debug('ErrorList====='+ErrorList);    
            
           List<Messaging.SingleEmailMessage> message_content = new List<Messaging.SingleEmailMessage>();
       
       //sending email to User 
          if(contRecords.ErrorCount >0){  
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'test@gmail.com'};
            mail.setToAddresses(toAddresses);
            mail.setSubject('Contact Failure Records list ' );
            mail.setPlainTextBody('Please find the list of failure records ' +ErrorList);
            message_content.add(mail); 
            Messaging.sendEmail(message_content); 
         }       
                       
       
    return contRecords;
    }
  public class contWrapper{
      
       @AuraEnabled public String records{get;set;}
       @AuraEnabled public Integer successCount{get;set{ successCount = Integer.valueOf(value); }}
       @AuraEnabled public Integer ErrorCount{get;set{ ErrorCount= Integer.valueOf(value); }}
     }  
}
Best Answer chosen by Salesforce seekar
SwethaSwetha (Salesforce Developers) 
HI,
Based on the provided code, it seems that the issue is with the formatting of the error message in the email body. The current email body is missing the details of the first error record.

To fix this, you can modify the code to create a separate string for each error record and then concatenate them into a single string to include in the email body.

Example code:
List<String> errorMessages = new List<String>();
for (integer i=0; i < result.size(); i++) {
    if(result.get(i).isSuccess()) {
        contRecords.successCount++;
    } else {
        contRecords.ErrorCount++;
        Database.Error dbError = result.get(i).getErrors().get(0);   
        String errorMessage = dbError.getMessage()+ ' '+' '+'for RecordName: '+(String)Conlist[i].get('Name');
        errorMessages.add(errorMessage);
    }
} 

//sending email to User 
if(contRecords.ErrorCount >0){  
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {'test@gmail.com'};
    mail.setToAddresses(toAddresses);
    mail.setSubject('Contact Failure Records list ' );
    mail.setPlainTextBody('Please find the list of failure records:\n' + String.join(errorMessages, '\n'));
    message_content.add(mail); 
    Messaging.sendEmail(message_content); 
}
Related:
https://developer.salesforce.com/forums/?id=9060G000000I148QAC
https://stackoverflow.com/questions/76480988/identify-the-error-record-while-inserting-in-salesforce-using-simple-salesforce
https://salesforce.stackexchange.com/questions/241989/how-to-capture-individual-exceptions-in-bulk-record-updates

If this information helps, please mark the answer as best. Thank you

All Answers

SwethaSwetha (Salesforce Developers) 
HI,
Based on the provided code, it seems that the issue is with the formatting of the error message in the email body. The current email body is missing the details of the first error record.

To fix this, you can modify the code to create a separate string for each error record and then concatenate them into a single string to include in the email body.

Example code:
List<String> errorMessages = new List<String>();
for (integer i=0; i < result.size(); i++) {
    if(result.get(i).isSuccess()) {
        contRecords.successCount++;
    } else {
        contRecords.ErrorCount++;
        Database.Error dbError = result.get(i).getErrors().get(0);   
        String errorMessage = dbError.getMessage()+ ' '+' '+'for RecordName: '+(String)Conlist[i].get('Name');
        errorMessages.add(errorMessage);
    }
} 

//sending email to User 
if(contRecords.ErrorCount >0){  
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {'test@gmail.com'};
    mail.setToAddresses(toAddresses);
    mail.setSubject('Contact Failure Records list ' );
    mail.setPlainTextBody('Please find the list of failure records:\n' + String.join(errorMessages, '\n'));
    message_content.add(mail); 
    Messaging.sendEmail(message_content); 
}
Related:
https://developer.salesforce.com/forums/?id=9060G000000I148QAC
https://stackoverflow.com/questions/76480988/identify-the-error-record-while-inserting-in-salesforce-using-simple-salesforce
https://salesforce.stackexchange.com/questions/241989/how-to-capture-individual-exceptions-in-bulk-record-updates

If this information helps, please mark the answer as best. Thank you
This was selected as the best answer
Salesforce seekarSalesforce seekar
Hi Swetha .....
I added like this
mail.setPlainTextBody('Please find the list of failure records:\n' + String.join(errorMessages, '\r\n'));  its working as expected...