1

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: [email protected]

Email should go as,

Hi Smith,

Below Email is does not exist in Contact records

Email: [email protected]

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

10
  • Do you have two email templates? So one will be used when you find a duplicate contact and one will be when the new contact is having unique email.
    – Shankish
    Jun 13, 2016 at 15:26
  • I don't have any email template as of now. I am looking for a solution/better approach to achieve the above requirement. Please let me know how to do it.
    – KSL
    Jun 13, 2016 at 15:27
  • 1
    why not just use SFDC OOB Duplicate Management?
    – cropredy
    Jun 13, 2016 at 15:36
  • @cropredy, The records are coming up from an integration and the records are getting inserted into salesforce, we need to check all our contacts and if the email id is not there, we need to send email to the login user. I am not sure how SFDC OOB duplicate management helps in this case... Can u please let me know how to approach to solve this issue
    – KSL
    Jun 13, 2016 at 15:39
  • After c.addError( errMsg);, you can write Apex code to send email to logged in user. Using Apex Email classes and methods.
    – Shankish
    Jun 13, 2016 at 15:40

3 Answers 3

2

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;

}

}

4
  • ok. So May I know what are the options that I can try it now. I really don't want to save that record in salesforce but want to send emails to the login users. what if we save the record first and delete it later, will that help us to send the email to user?
    – KSL
    Jun 14, 2016 at 13:24
  • Yes It'll help you to send email to Logged-In user. 1. Create a Check Box "IsContactExistWithEmail" on Contact. 2. Update this field in before insert if you found Contact with new email 3. In after Insert check if the field is true then create a List of new contact with new contact ids(because you can't perform DML operation on Trigger's Context in the same trigger) for your help I added Trigger Code, it allow to send email to logged in user and deleting the contact. Jun 14, 2016 at 15:59
  • 1
    Hi worked with some changes... Thanks a lot Dharmendra :)
    – KSL
    Jun 14, 2016 at 18:16
  • I added my code there I don't know how to remove the existing code.. can someone delete or change the post .. so that it will be helpful to others
    – KSL
    Jun 14, 2016 at 18:21
0
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);
              Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setToAddresses(new String[] { UserInfo.getUserEmail() });
            mail.setSubject('Your relvant subject');
            mail.setPlainTextBody('required information');
            Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {mail};
         Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        }
    }
}

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm

8
  • I tried your solution and its not sending an email to login user.Can we test by giving email id directly in code for testing purpose. Note: I am testing it in sandbox instance and email deliverability is set to all email
    – KSL
    Jun 13, 2016 at 15:58
  • Yes please. Try hardcoding email address.
    – Shankish
    Jun 13, 2016 at 16:03
  • I just tried in my org I am able to send email to the logged in user with the same code. Didn't change anything.
    – Shankish
    Jun 13, 2016 at 16:09
  • Hard coding also didn't worked. below is the code which I hardcoded mail.setToAddresses(new String[] { '[email protected]' });
    – KSL
    Jun 13, 2016 at 16:11
  • At the end can you debug, System.debug(results[0]); and check what was the result of the sent process.
    – Shankish
    Jun 13, 2016 at 16:30
0

Email does not sent until Apex Transaction is committed.
After Transaction failure even future method is not executed, So you can't even create asynchronous job to send email.

Note the following:

  • The email is not sent until the Apex transaction is committed.
  • The email address of the user calling the sendEmail method is inserted in the From Address field of the email header. All email that is returned, bounced, or received out-of-office replies goes to the user calling the method.
  • Maximum of 10 sendEmail methods per transaction. Use the Limits methods to verify the number of sendEmail methods in a transaction.
  • Single email messages sent with the sendEmail method count against the sending organization's daily single email limit. When this limit is reached, calls to the sendEmail method using SingleEmailMessage are rejected, and the user receives a SINGLE_EMAIL_LIMIT_EXCEEDED error code. However, single emails sent through the application are allowed.
  • Mass email messages sent with the sendEmail method count against the sending organization's daily mass email limit. When this limit is reached, calls to the sendEmail method using MassEmailMessage are rejected, and the user receives a MASS_MAIL_LIMIT_EXCEEDED error code.
  • Any error returned in the SendEmailResult object indicates that no email was sent.

Reference Links :

  1. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_forcecom_email_outbound.htm
2
  • ok. So May I know what are the options that I can try it now. I really don't want to save that record in salesforce but want to send emails to the login users
    – KSL
    Jun 14, 2016 at 8:51
  • After adding error to record every changes are rolled back, so for achieving functionality you are expecting we can follow these steps : 1. Create custom Boolean field on contact 2. In case of error condition set value to true and send email 3. create after insert trigger 4. delete all the records with error field true. Jun 14, 2016 at 17:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .