+ Start a Discussion
Pragnya PandaPragnya Panda 

Need to get Targetobjectid from Failure/ Successful records.

Hi All,

  i am trying  to fetch the Targetobjectid from SendEmailResult  object but i am not able to get that value.

 my functionality is :

I need to  send  Bulk Emails to different Contacts  using Send Email method like below:

 Messaging.sendEmail(emails,false); // Here emails is a List.

  Example :  Lets say i am sending 50 mails at a time  in that  48 mails are successfully sent and  2 are failed to send.

    Here i need to find what are the Mails failed and  it's related records (in this Scenario  case is my Object)

 for getting the SendEmailresults  code is below :

List<Messaging.SendEmailResult> sendEmailResults = Messaging.sendEmail(emails,false);
  for(Messaging.SendEmailResult sendEmailResult: sendEmailResults){

                 if(!sendEmailResult.isSuccess()){
                    system.debug(sendemailresult);
                }
                   
              }

 The sendEmailresult for  Failure records is       Messaging.SendEmailResult[getErrors=(Messaging.SendEmailError[getTargetObjectId=null;]);isSuccess=false;]

 The send Email Result for Successful Records is      Messaging.SendEmailResult[getErrors=();isSuccess=true;]

but in both ways  iam not able to get the  TargetObjectid .
 
i red in Salesforce docs  as below:

an error occurs that prevents sendEmail() from sending the email to one or more targets, each TargetObjectId for those targets has an associated error in SendEmailResult. A TargetObjectId that does not have an associated error in SendEmailResult indicates the email was sent to the target. If SendEmailResult has an error that does not have an associated TargetObjectId, no email was sent. 


  let me know am i doing anything wrong here and one morething   failure email    are due to  bouncing emails not because of  email address empty in contact.   
Thanks in Advance.

 
Best Answer chosen by Pragnya Panda
James LoghryJames Loghry
This is also somewhat of an issue for partial processing with Database.upsert, Database.insert, etc.

For retrieving the Ids from Database.UpsertResult class, you have to rely on the order of records that you pass into the call, since when an error occurs on insert, there is no Id.

For your mailing scenario this may look like:

Map<Id,Messaging.SendEmailResult> targetToResultMap = new Map<Id,Messaging.SendEmailResult>();
List<Messaging.SendEmailResult> sendEmailResults = Messaging.sendEmail(emails,false);
Integer i=0; 
for(Messaging.SendEmailResult sendEmailResult: sendEmailResults){
    targetToResultMap.put(emails.get(i).getTargetObjectId(),sendEmailResult);    
    i++;
}