Skip to main content The Trailblazer Community will be unavailable from 2/1/2025 to 2/2/2025. Please plan your activities accordingly.
Hello All,

I have a trigger which is after trigger and it is sending an email to the contact, my requiremnt is once I sent email I want to update one of field of my custom object. Can someone help with sample code.

Thanks.
1 answer
  1. Jul 20, 2018, 5:02 AM
    I have considered Contact object for time being. But you can replace Contact to any object later.

    Trigger

    ----------------------

    trigger SendEmailToAccount on Contact (after insert) {

        if(Trigger.isAfter){

            if(Trigger.isInsert ){ 

                //helper class for single email but bulk messages

                HelperContactTrigger.sendEmail(trigger.new);

            }

        }

        

        //

        Set<Id> allInsertedIds = trigger.newMap.keySet();

        List<Contact> contactList = new List<Contact>();

        for(Id eachRecordId : allInsertedIds){

            Contact contact = new Contact();

            contact.Id=eachRecordId;

            // add your field which you want to update.

            contactList.add(contact);

        }

        

        if(contactList!=null && !contactList.isEmpty()){

        update contactList;

        }

        

    }

    ---------------------

    Helper Class

    ----------------------

    public with sharing class HelperContactTrigger {

        //static method

        public static List<Contact> sendEmail(List<Contact> contacts) {

            //query on template object

            EmailTemplate et=[Select id from EmailTemplate where name=:'Sales: New Customer Email'];

            //list of emails

            List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

            //loop

            for(Contact con : contacts){

                //check for Account

                if(con.AccountId == null && con.Email != null){

                    //initiallize messaging method

                    Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

                    //set object Id

                    singleMail.setTargetObjectId(con.Id);

                    //set template Id

                    singleMail.setTemplateId(et.Id);

                    //flag to false to stop inserting activity history

                    singleMail.setSaveAsActivity(false);

                    //add mail

                    emails.add(singleMail);

                   //This will not send email to contact  

                   emails.setTreatTargetObjectAsRecipient(false);

                }

            }

            //send mail

            Messaging.sendEmail(emails);

            return contacts;

        }

    }

    https://salesforce.stackexchange.com/questions/38947/sending-email-notification-using-trigger​

    Please mark it best if it helps you. Thanks.

    Regards,

    Pawan Kumar
0/9000