I am having an issue with my trigger. So I created a trigger that sends emails to the Sales rep when a duplicate domain is detected in the leads. The domain is checked from the lead object to the contact object. My trigger works fine, just for one problem. So the problem is that if another field is updated within the Lead, the trigger sends another email. I do not want the trigger to send emails if other fields are updated only if the email is updated. Is there any way to go about solving this?
trigger FindDupes on Lead (before insert, before update) {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>(); //master list that will hold all the emails that we send out
for (Lead myLead : Trigger.new){
if(myLead.Domain__c != null){
List<Contact> dupes = [SELECT Domain__c FROM Contact
WHERE Domain__c = :myLead.Domain__c];
if(dupes.size() > 0 && myLead.IsConverted==False ){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> sendTo = new List<String>();
sendTo.add('[email protected]');
mail.setToAddresses(sendTo);
//mail.setReplyTo('[email protected]');
mail.setSenderDisplayName('Salesforce Administrator');
mail.setSubject('IMPORTANT MESSAGE');
String body = 'Hello' + ', ';
body+= 'the domain of the lead that just came in is already in our system.' + '**********';
body+= ' '+ ' Lead Name: ' + myLead.FirstName + ' ' + myLead.LastName + '**********';
body+= ' '+ ' Company Name: ' + myLead.Company;
mail.setHtmlBody(body);
mails.add(mail);
Messaging.sendEmail(mails);
}else{
myLead.Email = myLead.Email;
}
}
}
}