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
kabkab 

How to send email from Opportunity using email templates using Apex?

Is there a way I can send email to specific Account EmailID(Emailid is a custom field in the account) using templates?

Also I need to send email using Opportunity data that is in the template.

Mycode looks like this.

 

Messaging.SingleEmailMessage mail =

newMessaging.SingleEmailMessage();

List<String> tolist=newList<String>();

tolist.add('test@test.com');

mail.setCcAddresses(tolist);

mail.setToAddresses(tolist);

 

mail.setTargetObjectId(objOpp.AccountID);

// Specify who the email should be sent to. //mail.setWhatId(objOpp.tower__c);

mail.setTemplateId('00XC0000001SKoE');

 

Messaging.sendEmail(

newMessaging.SingleEmailMessage[] {mail});

 

I get error only Lead,User and Contact can be used to set the teargetid.

 

Thanks in advance for your help.

Navatar_DbSupNavatar_DbSup

Hi,


you cannot use like this mail.setTargetObjectId(objOpp.AccountID) because setTagerObjectId The ID of the contact, lead, or user to which the email will be sent. Hence my advice is to use Query on that Account email id and pass this value inside Toaddress value like this:

 

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> tolist=new List<String>();
string e1=[select id,AshishPackage__Email__c from account where id='00190000009YRjz'].AshishPackage__Email__c;
tolist.add(e1);
mail.setCcAddresses(tolist);
mail.setToAddresses(tolist);
mail.setTargetObjectId('00390000007QZoj');
// Specify who the email should be sent to. //mail.setWhatId(objOpp.tower__c);
mail.setTemplateId('00X90000000p14T');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.