+ Start a Discussion
uma52551.3972270309784705E12uma52551.3972270309784705E12 

Apex Trigger To Insert/Delete/Update a record

Hi All,

Any one please advise me how to write a trigger that will send an email to alert when that record is created or updated or deleted.. Thanks!
Best Answer chosen by uma52551.3972270309784705E12
MithunPMithunP

Hi Uma,

What is your parent object name that contains email field?

If Parent object is "User" then update your code like below.
 
trigger EventTeamMemberTrigger on Event_Team_Member__c (after insert,after update,before delete) {



if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate) ){

//Start of new code

set<id> pids = new set<id>()
for(Event_Team_Member__c eTM : Trigger.new){
    pids.add(eTM.Team_Member__c);  
}
map<id,User> pmap = new map<id,User>([select id,email from User Where id in: pids ]);
//End of new code
 
for (Event_Team_Member__c eTM : Trigger.new) 
{ 
  if(eTM.Team_Member__c != null){ 
    User tmm = pmap.get(eTM.Team_Member__c);
    String userEmail = tmm.email; // This is the Path Where I can get the Email Id of the Team_Member__c(user)
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {userEmail}; 
    mail.setToAddresses(toAddresses); 
    mail.setSubject('Automated email: Contact created/updated'); 
    String body = 'Contact created/updated' ; 
    mail.setPlainTextBody(body); 
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }
            
} 
}

if(trigger.isBefore && trigger.isDelete ){

//Start of new code

set<id> pids = new set<id>()
for(Event_Team_Member__c eTM : Trigger.old){
    pids.add(eTM.Team_Member__c);  
}
map<id,User> pmap = new map<id,User>([select id,email from User Where id in: pids ]);
//End of new code

for (Event_Team_Member__c eTM : Trigger.old) 
{ 
  if(eTM.Team_Member__c != null){
    User tmm = pmap.get(eTM.Team_Member__c);
    String userEmail = tmm.Email;
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
    String[] toAddresses = new String[] {userEmail}; 
    mail.setToAddresses(toAddresses); 
    mail.setSubject('Automated email: Contact deleted'); 
    String body = 'Contact deleted'; 
    mail.setPlainTextBody(body); 
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
  }
}

Best Regards,
Mithun.

All Answers

SonamSonam (Salesforce Developers) 
Sample code available on the Help and Training article on the link below :
https://help.salesforce.com/apex/HTViewSolution?id=000181297&language=en_US
MithunPMithunP
Hi Uma,

1. Create following trigger on "Contact" object.
2 Create contact records in contact object  //Make sure enter a valid email Id of you
3.Update contact records in contact object  //Make sure enter a valid email Id of you
4. Delete contact records in contact object  //Make sure enter a valid email Id of you

You will receive emails for all DML operations 
trigger ContactTrig on Contact (after insert, after update, before delete) { 
if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate) ){
for (Contact con : Trigger.new) 
{ 
String userEmail = con.email;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {userEmail}; 
mail.setToAddresses(toAddresses); 
mail.setSubject('Automated email: Contact created/updated'); 
String body = 'Contact created/updated' ; 
mail.setPlainTextBody(body); 
Messaging.sendEmail(new Messaging.SingleEMailMessage[]{mail});
} 
}

if(trigger.isBefore && trigger.isDelete ){
for (Contact con : Trigger.old) 
{ 
String userEmail = con.email;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
String[] toAddresses = new String[] {userEmail}; 
mail.setToAddresses(toAddresses); 
mail.setSubject('Automated email: Contact deleted'); 
String body = 'Contact deleted'; 
mail.setPlainTextBody(body); 
Messaging.sendEmail(new Messaging.SingleEMailMessage[]{mail});
} 
}

}
Mark it as Best Answer, if it solves your issue.

Best Regards,
Mithun.
uma52551.3972270309784705E12uma52551.3972270309784705E12
Hi Mithun,

Thanks for your help! I am getting the below error when I am using the above code for my object.

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger EventTeamMemberTrigger caused an unexpected exception, contact your administrator: EventTeamMemberTrigger: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : null: []: Trigger.EventTeamMemberTrigger: line 18, column 1

It is showing Error here : Messaging.sendEmail(new Messaging.SingleEMailMessage[]{mail}); Please help me 

 
MithunPMithunP
Hi Uma,

Did you created contact record with valid email id.

Could you share your complete trigger code.

Best Regards,
Mithun.
uma52551.3972270309784705E12uma52551.3972270309784705E12
trigger EventTeamMemberTrigger on Event_Team_Member__c (after insert,after update,before delete) {

if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate) ){
for (Event_Team_Member__c eTM : Trigger.new) 

String userEmail = eTM.Team_Member__r.email; // This is the Path Where I can get the Email Id of the Team_Member__c(user)
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {userEmail}; 
mail.setToAddresses(toAddresses); 
mail.setSubject('Automated email: Contact created/updated'); 
String body = 'Contact created/updated' ; 
mail.setPlainTextBody(body); 
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
            

}

if(trigger.isBefore && trigger.isDelete ){
for (Event_Team_Member__c eTM : Trigger.old) 

String userEmail = eTM.Team_Member__r.Email;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
String[] toAddresses = new String[] {userEmail}; 
mail.setToAddresses(toAddresses); 
mail.setSubject('Automated email: Contact deleted'); 
String body = 'Contact deleted'; 
mail.setPlainTextBody(body); 
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
MithunPMithunP
Hi Uma,

Got It, You won't get parent object deatils (except Id) on inserting a new record, so your code (eTM.Team_Member__r.email) won't work.

You should query the parent object details then you have to use email field.

Here is the updated version of trigger. Try to merge into your actual code.
 
trigger EventTeamMemberTrigger on Event_Team_Member__c (after insert,after update,before delete) {



if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate) ){

//Start of new code

set<id> pids = new set<id>()
for(Event_Team_Member__c eTM : Trigger.new){
    pids.add(eTM.Team_Member__c);  
}
map<id,Event_Team_Member__c> pmap = new map<id,Event_Team_Member__c>([select id,email__c from Team_Member__c Where id in: pids ]);
//End of new code
 
for (Event_Team_Member__c eTM : Trigger.new) 
{ 
  if(eTM.Team_Member__c != null){ 
    Team_Member__c tmm = pmap.get(eTM.Team_Member__c);
    String userEmail = tmm.email__c; // This is the Path Where I can get the Email Id of the Team_Member__c(user)
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {userEmail}; 
    mail.setToAddresses(toAddresses); 
    mail.setSubject('Automated email: Contact created/updated'); 
    String body = 'Contact created/updated' ; 
    mail.setPlainTextBody(body); 
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }
            
} 
}

if(trigger.isBefore && trigger.isDelete ){
for (Event_Team_Member__c eTM : Trigger.old) 
{ 
String userEmail = eTM.Team_Member__r.Email;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
String[] toAddresses = new String[] {userEmail}; 
mail.setToAddresses(toAddresses); 
mail.setSubject('Automated email: Contact deleted'); 
String body = 'Contact deleted'; 
mail.setPlainTextBody(body); 
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
}


Best Regards,
Mithun.
 
uma52551.3972270309784705E12uma52551.3972270309784705E12
For Delete It is not working Saying Null values String userEmail = eTM.Team_Member__r.Email;
MithunPMithunP
Hi Uma,

Below is updated one for Delete.
trigger EventTeamMemberTrigger on Event_Team_Member__c (after insert,after update,before delete) {



if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate) ){

//Start of new code

set<id> pids = new set<id>()
for(Event_Team_Member__c eTM : Trigger.new){
    pids.add(eTM.Team_Member__c);  
}
map<id,Event_Team_Member__c> pmap = new map<id,Event_Team_Member__c>([select id,email__c from Team_Member__c Where id in: pids ]);
//End of new code
 
for (Event_Team_Member__c eTM : Trigger.new) 
{ 
  if(eTM.Team_Member__c != null){ 
    Team_Member__c tmm = pmap.get(eTM.Team_Member__c);
    String userEmail = tmm.email__c; // This is the Path Where I can get the Email Id of the Team_Member__c(user)
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {userEmail}; 
    mail.setToAddresses(toAddresses); 
    mail.setSubject('Automated email: Contact created/updated'); 
    String body = 'Contact created/updated' ; 
    mail.setPlainTextBody(body); 
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }
            
} 
}

if(trigger.isBefore && trigger.isDelete ){

//Start of new code

set<id> pids = new set<id>()
for(Event_Team_Member__c eTM : Trigger.old){
    pids.add(eTM.Team_Member__c);  
}
map<id,Event_Team_Member__c> pmap = new map<id,Event_Team_Member__c>([select id,email__c from Team_Member__c Where id in: pids ]);
//End of new code

for (Event_Team_Member__c eTM : Trigger.old) 
{ 
  if(eTM.Team_Member__c != null){
    Team_Member__c tmm = pmap.get(eTM.Team_Member__c);
    String userEmail = tmm.Email__c;
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
    String[] toAddresses = new String[] {userEmail}; 
    mail.setToAddresses(toAddresses); 
    mail.setSubject('Automated email: Contact deleted'); 
    String body = 'Contact deleted'; 
    mail.setPlainTextBody(body); 
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
  }
}



Best Regards,
Mithun.
uma52551.3972270309784705E12uma52551.3972270309784705E12
Team_Member__c tmm = pmap.get(eTM.Team_Member__c); Here Team_Member__c is not an Object so it is giving error of invalid Type
MithunPMithunP

Hi Uma,

What is your parent object name that contains email field?

If Parent object is "User" then update your code like below.
 
trigger EventTeamMemberTrigger on Event_Team_Member__c (after insert,after update,before delete) {



if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate) ){

//Start of new code

set<id> pids = new set<id>()
for(Event_Team_Member__c eTM : Trigger.new){
    pids.add(eTM.Team_Member__c);  
}
map<id,User> pmap = new map<id,User>([select id,email from User Where id in: pids ]);
//End of new code
 
for (Event_Team_Member__c eTM : Trigger.new) 
{ 
  if(eTM.Team_Member__c != null){ 
    User tmm = pmap.get(eTM.Team_Member__c);
    String userEmail = tmm.email; // This is the Path Where I can get the Email Id of the Team_Member__c(user)
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {userEmail}; 
    mail.setToAddresses(toAddresses); 
    mail.setSubject('Automated email: Contact created/updated'); 
    String body = 'Contact created/updated' ; 
    mail.setPlainTextBody(body); 
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
    }
            
} 
}

if(trigger.isBefore && trigger.isDelete ){

//Start of new code

set<id> pids = new set<id>()
for(Event_Team_Member__c eTM : Trigger.old){
    pids.add(eTM.Team_Member__c);  
}
map<id,User> pmap = new map<id,User>([select id,email from User Where id in: pids ]);
//End of new code

for (Event_Team_Member__c eTM : Trigger.old) 
{ 
  if(eTM.Team_Member__c != null){
    User tmm = pmap.get(eTM.Team_Member__c);
    String userEmail = tmm.Email;
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
    String[] toAddresses = new String[] {userEmail}; 
    mail.setToAddresses(toAddresses); 
    mail.setSubject('Automated email: Contact deleted'); 
    String body = 'Contact deleted'; 
    mail.setPlainTextBody(body); 
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
  }
}

Best Regards,
Mithun.
This was selected as the best answer
uma52551.3972270309784705E12uma52551.3972270309784705E12
thank you I am getting result now..thank you very much for your help... can you please help me in writing the apex test class for this..


trigger EventTeamMemberTrigger on Event_Team_Member__c (after insert,after update,Before delete) { if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate) ){ Event_Team_Member__c neweTM = [select Id,Team_Member__r.Email,Team_Member__r.Name from Event_Team_Member__c Where id = :trigger.newMap.keySet()]; for (Event_Team_Member__c eTM : Trigger.new)  {  String userEmail = neweTM.Team_Member__r.Email; Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {userEmail};  mail.setToAddresses(toAddresses);  mail.setSubject('Automated email: Event Team Member Created/Updated');  String body = 'This Message is to alert you that the Event Team Member named' + neweTM.Team_Member__r.Name+' has been created/updated.' ;  mail.setPlainTextBody(body);  Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});           }  } if(trigger.isBefore && trigger.isDelete ){ Event_Team_Member__c oldeTM = [select Id,Team_Member__r.Email,Team_Member__r.Name from Event_Team_Member__c Where id = :trigger.oldMap.keySet()]; Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); for (Event_Team_Member__c eTM : Trigger.old)   {  String[] toAddresses = new String[] {oldeTM.Team_Member__r.Email};  email.setToAddresses(toAddresses);  email.setSubject('Automated email: Event Team Member Deleted');  String body = 'This message is to alert you that the Event Team Member named ' + oldeTM.Team_Member__r.Name + ' has been deleted.';  email.setPlainTextBody(body);  } Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});  } }
 
MithunPMithunP
Hi Uma,

Here is the test class, if any mandatoty fields exists for Event_Team_Member__c object then add it on line number 11 along with name and
Team_Member__c .
@isTest (SeeAlldata = true)
                    
public class TestTrigger {
   public static testMethod void testRunAs() {
      Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
      User u = new User(Alias = 'standtd', Email='standarduser@testorg.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
      insert u;
      Event_Team_Member__c evtm = new Event_Team_Member__c(Name = 'TestRec', Team_Member__c = u.id);
      insert evtm;
      
   }
}

Please mark it as Best Answer, if it solves your problem.

Best Regards,
Mithun.
 
uma52551.3972270309784705E12uma52551.3972270309784705E12
Hi Mithun,

In the above code It is working for only one user not for bulk because I am using neweTM instead of eTM. If iam using eTM it is throughing an error Invalid Email Address. Please let me know what was my mistake.

trigger EventTeamMemberTrigger on Event_Team_Member__c (after insert,after update,Before delete) { if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate) ){ Event_Team_Member__c neweTM = [select Id,Team_Member__r.Email,Team_Member__r.Name from Event_Team_Member__c Where id = :trigger.newMap.keySet()]; for (Event_Team_Member__c eTM : Trigger.new)  { 
String userEmail = neweTM.Team_Member__r.Email;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {userEmail}; 
mail.setToAddresses(toAddresses); 
mail.setSubject('Automated email: Event Team Member Created/Updated');  String body = 'This Message is to alert you that the Event Team Member named' + neweTM.Team_Member__r.Name+' has been created/updated.' ;  mail.setPlainTextBody(body); 
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});          
}
  }

if(trigger.isBefore && trigger.isDelete ){ Event_Team_Member__c oldeTM = [select Id,Team_Member__r.Email,Team_Member__r.Name from Event_Team_Member__c Where id = :trigger.oldMap.keySet()]; Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
for (Event_Team_Member__c eTM : Trigger.old)   { 
String[] toAddresses = new String[] {oldeTM.Team_Member__r.Email}; 
email.setToAddresses(toAddresses); 
email.setSubject('Automated email: Event Team Member Deleted');  String body = 'This message is to alert you that the Event Team Member named ' + oldeTM.Team_Member__r.Name + ' has been deleted.';  email.setPlainTextBody(body);
  }
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email}); 
}
}