You need to sign in to do that
Don't have an account?
Masechaba Maseli 8
SingleEmailMessage with targetObject and templateId
Hi
My scenario is that I would like to notify all contacts for an account about a new custom record being created. There is no relationship between the custom object and contacts.
The code that I am using allows me to send the email but it is in the contact context and I am not certain how to set a SentToAddress and a TargetObjectId.
My scenario is that I would like to notify all contacts for an account about a new custom record being created. There is no relationship between the custom object and contacts.
The code that I am using allows me to send the email but it is in the contact context and I am not certain how to set a SentToAddress and a TargetObjectId.
public class SendEmailTemplatesToAccountContacts { @InvocableMethod public static void sendEmail(List<Account> acc) { Shipment_Order__c so = new Shipment_Order__c (); String sourceAccountId = String.valueOf(acc[0].Id); List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>(); List<Contact> contactsToEmail = [SELECT Id FROM Contact WHERE AccountId = :sourceAccountId]; Id templateId = [SELECT Id, Name FROM EmailTemplate WHERE Name = 'New Shipment Notification Supplier'].Id; for(Contact con: contactsToEmail){ Messaging.SingleEmailMessage email = new messaging.SingleEmailMessage(); email.setTemplateId(templateId); email.setTargetObjectId(con.Id); email.setSaveAsActivity(true); //or true if you want to save as an activity email.setSenderDisplayName('Sender Display Name'); //Here if you want to change the sender name emailsToSend.add(email); } Messaging.sendEmail(emailsToSend); } }
- Please have you got a chance to look the below link for SingleEmailMessage setTargetObjectId.Please refer.
- https://salesforce.stackexchange.com/questions/82583/singleemailmessage-settargetobjectid-but-do-not-send-to-target
Let us know if it helps.Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.
Thanks
Rahul Kumar
That made a lot of sense, I have adjusted the code but now I am getting an error that the TargetObjectId is missing.