Skip to main content
Masechaba Maseli (TecEx) a posé une question dans #Apex
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. 

 

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);

  }

  

}

 
2 réponses
  1. 11 oct. 2017, 13:54
    Hi Rahul

    That made a lot of sense, I have adjusted the code but now I am getting an error that the TargetObjectId is missing. 

    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, Email

    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();

    List<String> sendTo = new List<String>();

    sendTo.add(con.Email);

    email.setTemplateId(templateId);

    email.setWhatId(so.Id);

    email.setTargetObjectId(so.Id);

    email.setTreatTargetObjectAsRecipient(False);

    email.setToAddresses(sendTo);

    email.setSaveAsActivity(true); //or true if you want to save as an activity

    email.setSenderDisplayName('TecEx Support'); //Here if you want to change the sender name

    emailsToSend.add(email);

    }

    Messaging.sendEmail(emailsToSend);

    }

    }

     
0/9000