3
List<Opportunity > oppList = [SELECT id,name,account.id from Opportunity];

    for ( Opportunity opp : oppList)
    {
        System.debug(opp.account.id);
        List<Lead > leads = [SELECT id,name,owner.id,email FROM Lead WHERE ConvertedAccountId = :opp.account.id];
        If(!leads.isEmpty()){
            // Send Email to leads email adddress
            EmailTemplate templateId = [Select id from EmailTemplate where name = 'EmailTemplate3'];
            User leadOwner = [Select id,email,firstname,lastname from User where id = :leads[0].owner.id];

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTemplateId(templateId.id);
            mail.setToAddresses(leads[0].email.split(':'));
            mail.setReplyTo(leadOwner.Email);
            mail.setSenderDisplayName(leadOwner.firstname + leadOwner.lastname);
            mail.setBccSender(false);
            mail.setTargetObjectid(leads[0].id);
            mail.setwhatId(leadOwner.id);
            mail.SaveAsActivity = false;
            List<Messaging.sendEmailResult> results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.CONFIRM, ' Email sent successfully.'));
            system.debug(results);
        }
    }
System.EmailException: SendEmail failed. First exception on row 0; first error: CANNOT_UPDATE_CONVERTED_LEAD, Invalid targetObjectId 00QO0000002Cx1BMAS: []

i get this error while trying to send an email. The lead is converted. Is it setTargetObjectid property that is causing error. Is there any workaround.

3
  • Is your code called from trigger ?Could you share that as well – Mohith Shrivastava Aug 11 '14 at 12:28
  • No i am running from execute anonymous apex window. I will later run it as scheduled apex code. – Shanker Paudel Aug 11 '14 at 12:33
  • Can you add query filter with isconverted=false .You cant use converted Lead for this process – Mohith Shrivastava Aug 11 '14 at 13:16
2

You are correct that Target Object Id is causing it, since Lead is converted. You should be able to get ConvertedContactId from the lead and use it as a TargetObjectId to avoid this error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.