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) {
/** * 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() ;
}
}