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

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). Sep 28 '18 at 10:48

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.