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
ketan mehtaketan mehta 

Send mail and record as activity history for an object issue.

Hi,
   I am tring to send email from trigger and required to log as Activity History for an opportunity. I am setting mail.targetObjectId as opportunityId. I am getting an exeption like : INVALID_TYPE_FOR_OPERATION, Only Users, Contact or Lead allowed for targetObjectId. I read some articles on Google and mentioned that it is not possible. Is there any way to achieve the same?

Thanks in advance.
Ketan



Best Answer chosen by ketan mehta
ketan mehtaketan mehta
Hi Anup,
   Thanks for guiding towards right path. Finally I am able to achieve the same as below. Apart from setting the targetObjectId, we need to set mail.setWhatId value to the object id.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'xxxxx@yahoo.co.in'};
        mail.setToAddresses(toAddresses);
        mail.setBccSender(false);
        mail.setWhatId('0069000000LKxxx');//OpportunityId
        mail.setTargetObjectId('00390000012nwww'); //ContactId
        mail.setSaveAsActivity(true);
        mail.setSubject('test mail');
        mail.setPlainTextBody('hi there');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

Regards,
Ketan Mehta

All Answers

Anup JadhavAnup Jadhav
You can get hold of the user record that is the owner of this opportunity and set the mail.targetObjectId as the userId.
ketan mehtaketan mehta
Hi Anup,
   Thanks for guiding towards right path. Finally I am able to achieve the same as below. Apart from setting the targetObjectId, we need to set mail.setWhatId value to the object id.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'xxxxx@yahoo.co.in'};
        mail.setToAddresses(toAddresses);
        mail.setBccSender(false);
        mail.setWhatId('0069000000LKxxx');//OpportunityId
        mail.setTargetObjectId('00390000012nwww'); //ContactId
        mail.setSaveAsActivity(true);
        mail.setSubject('test mail');
        mail.setPlainTextBody('hi there');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

Regards,
Ketan Mehta
This was selected as the best answer