You need to sign in to do that
Don't have an account?
aparna d 1
send email notification using email templates in apex class
Hi everyone,
I am stuck to send email notification using email templates. Error is coming from whatId,targetobjectid. Can anyone help on this.Below is my code
I am stuck to send email notification using email templates. Error is coming from whatId,targetobjectid. Can anyone help on this.Below is my code
Id LTA = Schema.SObjectType.opportunity.getRecordTypeInfosByName().get('Service').getRecordTypeId(); Messaging.SingleEmailMessage mail= new Messaging.SingleEmailMessage(); List < Messaging.SingleEmailMessage > allmails = new List < Messaging.SingleEmailMessage > (); List<test__c> BRElst = new List<test__c>(); list<Id> CAMuser= new list<Id>(); set<string> CAMmail= new set<string>(); list<String> emailAddresses = new list<String>(); List<user> lstuser = new List<user>(); if( subopp.Business_Unit__c != null && subopp.recordtypeId == LTA ){ BRElst = [select id,CS_Corp_Acc_Manager__c from test__c where Business_Unit__c=:subopp.Business_Unit__c ]; System.debug ('BREList size'+BRElst.size()); for(test__c bre : BRElst) { CAMuser.add(bre.CS_Corp_Acc_Manager__c); } if( CAMuser!=null) { lstuser = [select id,Email,firstName,lastName from User where ID IN:CAMuser]; } EmailTemplate templateId = [Select id from EmailTemplate where name = 'sampletemplate']; for(BigMachines__c bq:relatedQuotes ){ If (bq.AddCAMtoPDR__c == false){ for(user u: lstuser ){ CAMmail.add(u.Email); System.debug('CAMmail' +CAMmail); emailAddresses.addAll(CAMmail); if(!emailAddresses.isEmpty()){ mail.setTemplateID(templateId.Id); mail.setToAddresses(emailAddresses); mail.setTargetObjectId(u.id); mail.setWhatId(apprecord.id); mail.setSaveAsActivity(false); allmails.add(mail); try{ Messaging.sendEmail(allmails); } catch(Exception e){ system.debug('-------------exception------'+e); } }
The issue is due to you are using the user Id in setTargetObjectId and using some custom object WhatId's.
If you want to use what Id then in setTargetObjectId you must have to use the Contact Id it won't allows any other Id's.
If you don't use ant whatId's then you can use the setTargetObjectId as User,Contact, or Lead.
So create some dummy contact record or test contact record for this and use that id in setTargetObjectId as hardcoded or use custom label as mentioned in below link
https://salesforce.stackexchange.com/questions/72516/why-cant-i-use-settargetobjectiduserid-and-setwhatid
Please read the below document carefully in setTargetObjectId and WhatId Methods then you will understand.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm
Can you please Let me know if it helps or not!!!
If it helps don't forget to mark this as a best answer!!!
Thanks,
Maharajan.C