[SalesForce] Verify Contact Email address. If Email is not present send an email to login user

I am looking for a specific requirement where I need to send an email login user whenever the user is creating a new Contact in Salesforce. If any contact exist with the same email Id, I need to send an email to login user and do not allow to create the contact.

I tried with a before insert trigger by searching in stack exchange and it allows me not to insert a new record with different email id.

I need help on how to sent a particular email template notification to login user with the details that I am entering while creation of Contact record.

Ex: If My contact details like,

Name: Smith
Email: smith.k@gmail.com

Email should go as,

Hi Smith,

Below Email is does not exist in Contact records

Email: smith.k@gmail.com

Below is my code trigger.

trigger triggerOnContact on Contact (before insert) {
    final String errMsg = 'The Email is Not available in the Contacts ';
    Set< String > emailSet = new Set< String >();
    for( Contact c : Trigger.new ) emailSet.add( c.Email );
    Map< String, Id > duplicateContactMap = new Map< String, Id >();
    for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
        duplicateContactMap.put( c.Email, c.Id );
    for( Contact c : Trigger.new ){
        if(!duplicateContactMap.containsKey(c.Email)){
            c.addError( errMsg);
        }
    }
}

Please help me how to implement the requested logic.. Thanks in advance

Best Answer

I would like to clarify something that, the email is not sent until the Apex transaction is committed.

Here are two links related to this situation:- http://help.salesforce.com/HTViewSolution?id=000006765 https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_forcecom_email_outbound.htm

Here is code for forcefully sendEmail to Logged In User.

trigger triggerOnContact on Contact (before insert, after insert) {

    Map<String,Contact> existingContactMap= new Map<String,Contact>(); //creating Map of contact with email you, because you can use other field while sending email
    Map<String,String> emailMsg = new Map<String,String>();

if(trigger.isBefore){
    Set<String> emailSet =new Set<String>();
    for(Contact contactObj : trigger.new){ 
        if(String.isNotBlank(contactObj.Email)) emailSet.add(contactObj.Email); 
    }
    For(List<Contact> contacts : [SELECT Name, Email From Contact WHERE Email in: emailSet ]){
        for(Contact contactObj : contacts){
            if(!existingContactMap.containsKey(contactObj.Email)){
                existingContactMap.put(contactObj.Email,contactObj);
                emailMsg.put(contactObj.Email,contactObj.Name);
            }
        }
    }
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    for(Contact contactObj : trigger.new){
        if(String.isNotBlank(contactObj.Email)){
            if(!existingContactMap.containsKey(contactObj.Email)){
                contactObj.IsContactExistWithEmail__c=true;//for deleting records
                mails.add(sendErrorEmail(contactObj.Email,existingContactMap, emailMsg));
                // contactObj.addError('The Email \''+ contactObj.Email + '\' is already available in the Contact.');
            }
        }
    }
    if(mails.size()>0)
        Messaging.sendEmail(mails); 
} else{
    List<Contact> contactToDelete = new List<Contact>();
    for(Contact contactObj : trigger.new){
        if(contactObj.IsContactExistWithEmail__c)
            contactToDelete.add(new Contact(id=contactObj.id));
        }
        if(contactToDelete.size()>0)
            delete contactToDelete;
    }

/** * method is used to creating Emails **/ private Messaging.SingleEmailMessage sendErrorEmail(String email,Map existingContactMap1, Map emailMsg1){ List toAddresses = new List{UserInfo.getUserEmail()} ; //getting Login user's Email System.debug(toAddresses); //Sending Mail Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage() ;

// Assign the addresses for the To and CC lists to the mail object
mail.setToAddresses(toAddresses);

//Email subject to be changed
mail.setSubject('Contact already exist with Email');

//Body of email
mail.setHtmlBody('Hi '  + emailMsg1.get(email)
                        +',\nBelow Email is does not exist in Contact records.\nEmail:'+email
                        +'\n so we Deleted the record.');
return mail;

}

}