0

I am trying to send an email to a contact owner so I passed contact ownerID instead of contact ID, now the user is getting the emails as expected but the merge fields are not working as I am not passing contact Id anywhere.

Can someone please suggest if is there any way to send emails to contact owners only and simultaneously use contact merge fields.

Contact Cont = [SELECT Id, ownerID FROM Contact where name = 'Alan Johnson' LIMIT 1];

  EmailTemplate ETemp = [SELECT ID FROM EmailTemplate WHERE name = 'ContactTemplate' Limit 1];

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.targetobjectid = cont.ownerID;
        email.setTemplateId(ETemp.id);
        email.saveAsActivity = false;
        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});

1 Answer 1

1

I came up with this solution :

    Contact Cont = [SELECT Id, ownerId, owner.Email, AccountId FROM Contact where name = 'Alan Johnson' LIMIT 1];
    EmailTemplate ETemp = [SELECT ID FROM EmailTemplate WHERE name = 'MyTestTemplate' Limit 1];

    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    email.targetobjectid = cont.Id;
    email.setTemplateId(ETemp.id);
    email.saveAsActivity = false;
    email.setTreatTargetObjectAsRecipient(false);
    email.setToAddresses(new List<string> {cont.owner.email});
    Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
1
  • 1
    In last update, I eliminated soql for user object. We can fetch owner email in single soql (contact one). Commented Sep 28, 2018 at 10:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .