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
buggs sfdcbuggs sfdc 

Send email to contact related account owner

HI 

can any one help me out to Send an email to contacts related account owner through apex.

Thanks in advance
SotosSotos
Using the setTargetObjectId you can set the ownerId as the recepient.
 
Account a = [Select OwnerId From Account Limit 1];

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.SetSubject('Test Email');
mail.setTargetObjectId(a.OwnerId);
mail.setTreatTargetObjectAsRecipient(true);
mail.setPlainTextBody('Email body');
mail.setSaveAsActivity(false);

Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail}, true);

 
buggs sfdcbuggs sfdc
Thank you so much for the quick reply,will it also works for contact related account?
Here is my existing code,now i wanted to make it work for contact related account even.
String TEMPLATE_ID = 'my template';
        
        Map<String, String> mapAccId2OwnerId = new Map<String, String>();
        contact c =[SELECT id,Account.OwnerId, AccountId,Email FROM Contact WHERE Id = :conId];
          if (c.AccountId!=NULL) mapAccId2OwnerId.put(c.AccountId, c.Account.OwnerId);
        Map<Id, User> mapUser = new Map<Id, User>([SELECT Id, Name, Email FROM USER WHERE Id IN :mapAccId2OwnerId.values()]);
        System.debug('mapUser===='+mapUser);

        Messaging.SingleEmailMessage[] emails = new Messaging.SingleEmailMessage[]{};
         Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

            message.setTemplateId(TEMPLATE_ID);
            message.setSaveAsActivity(true);
            message.setTargetObjectId(conId);
            //message. setCcAddresses(repname);
            //message.setWhatId(c.Id);
            
            if (c.AccountId!=NULL) message.setCcAddresses(new String[]{mapUser.get(mapAccId2OwnerId.get(c.AccountId)).Email});
            emails.add(message);
        if(!Test.isRunningTest()) Messaging.sendEmail(emails);