+ Start a Discussion
niven sfniven sf 

Hi! If an email field value is updated in contact object then an email will be send to users email with old email value and updated email value, How to write apex code for this? Please help me

Waqar Hussain SFWaqar Hussain SF
trigger ContactTrigger on Contact(after update) {

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

    list < OrgWideEmailAddress > owa = new list < OrgWideEmailAddress > ();
    owa = [select id, DisplayName, Address from OrgWideEmailAddress limit 1];

    for (contact cont: trigger.new) {
        if (trigger.OldMap.get(cont.Id).Email != cont.Email) {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            string HTMLBody = 'Hi ' + cont.Name + ', <br/><br/>';
            HTMLBody += 'Your Email has been changed. <br/><br/>';
            HTMLBody += '<b>Previous Email:</b> ' + trigger.OldMap.get(cont.Id).Email + '<br/>';
            HTMLBody += '<b>New Email:</b> ' + cont.Email + '<br/>';
            HTMLBody += 'Thanks';
            mail.setHtmlBody(HTMLBody);
            mail.SetSubject('Email Changed');
            list < string > toAddress = new list < string > ();
            toAddress.add(cont.Email);
            mail.setToAddresses(toAddress);
            mail.setSaveAsActivity(true);
            mail.setOrgWideEmailAddressId(owa[0].id);
            mail.setTargetObjectId(cont.Id);
            EmailsToSend.add(mail);
        }
    }

    if (EmailsToSend.size() > 0)
        Messaging.SendEmailResult[] results = Messaging.sendEmail(EmailsToSend, true);
}