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
DJ 367DJ 367 

How to update field after sending Email notification

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.
PawanKumarPawanKumar
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