function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Stephen02Stephen02 

Email to case - create contact record and associate to account record

Hi - I am using Salesforce's email to case functionality  (it's on-demand) and I have a trigger that automatically creates a new Contact record (if he contact's email address is not already in the system). 

What I am now trying to figure out is how to add this Contact record (created above) to a specific Account record that I call General Consumer?

Thanks. 
Best Answer chosen by Stephen02
BALAJI CHBALAJI CH
Hi Stephen,

Please find below the modified code. I have queried the Account record with name 'General Consumer' and associated it with the new inserting contact.
trigger CreateNewContact on EmailMessage (before insert) {
    
    //List and define local vars.
    List<Contact> contactList = new List<Contact>();
    List<Case> caseList = new List<Case>();
    string CaseId, ContactId, ContactEmail, EmailFromName, strFirstName, strpart, strLastName;
    
    //Querying account record whose name is General Consumer
    account ac = [select id, name from account where name =: 'General Consumer' limit 1];
    
    // Iterate over EmailMessages that are in this trigger and get caseId and EmailFromName.
    for(EmailMessage EM:Trigger.New) {
        
        // Get the CaseId to be associate with the new Contact.
        for (Case c: [SELECT Id, SuppliedName FROM Case  WHERE Id = :EM.ParentId]) {
            CaseId = c.Id;
            
            //if the suppliedName exists then prepare to parse out FirstName and LastName, 
            //otherwise, they will be left blank when inserted into case.
            if (c.SuppliedName.length() > 0) {
                EmailFromName = c.SuppliedName;
            }
            else {
                EmailFromName = ' ';
            }  
        }
        
        //Parse string for FirstName of sender email.
        strFirstName = EmailFromName.substring(0, EmailFromName.indexOf(' '));
        
        //Parse string for LastName of sender email.
        strLastName = EmailFromName.substring(EmailFromName.LastIndexOf(' '), EmailFromName.length());
        
        //Create Contact Record with Info. 
        contactList.add(new Contact(FirstName= strFirstName,
                                    LastName = strLastName,
                                    Email= EM.FromAddress,
                                    AccountId = ac.Id)); //Associating Account record Id to the new contact
        
        //Save Email for later query.
        ContactEmail = EM.FromAddress;
        
    }
    
    // Try catch statement to catach any errors and report them to the system logs.
    try{    
        
        //Insert the Contact Record into db.
        if (contactList.size() > 0) {
            insert contactList; 
        }
        
        //Loop through the new cases to Update records with New Contact ID.
        for (Case ca : [SELECT Casenumber, ContactId FROM Case WHERE Id = :CaseId]) {
            
            //Loop through the Contact to get the new ContactId to update into the cases.
            for (Contact newContact : [SELECT Email, Id FROM Contact WHERE Email = :ContactEmail]) {
                //Update Case Record with new ContactId.
                ca.ContactId= newContact.Id;
                //ca.Subject = ca.Subject + 'newContactId = ' + newContact.Id;
                caseList.add(ca);
            }
        }
        
        //Update the Case Record into db.
        if (caseList.size() > 0) 
        {
            update caseList;
        }  
        
        // Try catch statement to catach any errors and report them to the system logs.
    }
    catch(DmlException de )
    {
        System.debug(de); 
    } 
}

Please let me know if that works for you.

Best Regards,
BALAJI

All Answers

Shashikant SharmaShashikant Sharma
Hi Stephen,

You jsut need to make a SOQL in your trigger code to find General Consumer account and assign it to contct record.
 
List<Account> accts = [ Select Id From Account Where Name = 'General Consumer' Limit 1];

Account acc = accts.size() >0 ? accts.get(0).Id : new Account();

then in your trigger you could just do
 
con.AccountId = acc.Id;

If you could post your trigger may be I could tell you where to make changes and add this code.

Thanks
Shashikant

 
BALAJI CHBALAJI CH
Hi Stephen,

You  can query that particular account so called General Consumer and assign its ID to the contact's AccountId.
Please find below snippet.
account account = [select id, name from account where name =: 'General Consumer'];
contact contact = new contact();
contact.FirstName = 'First Name';
contact.LastName = 'Last Name';
contact.AccountId = account.id;

insert contact;
Please let me know if that helps you.

Best Regards,
BALAJI

 
Ravi Dutt SharmaRavi Dutt Sharma
As mentioned by Shashikant, you can query the Account record and associate the id of account to contact. Since your account name is fixed and if you do not want to do an additional SOQL query, store the account id in a custom setting, retreive it in your code and assign it to the contact record that you are creating.
Stephen02Stephen02
Hi Shashikant and Balaji - Thanks for your reply. Below is my trigger which currently ONLY creates a new contact record when an email comes into Salesforce that is not recognized.  I just need to know how to update/write the below trigger so that the Contact record is automatically associated to my Account record name called "General Consumer" (the Account ID is this: 001q000000SjaCj)


trigger CreateNewContact on EmailMessage (before insert) {
    
    //List and define local vars.
    List<Contact> contactList = new List<Contact>();
    List<Case> caseList = new List<Case>();
    string CaseId, ContactId, ContactEmail, EmailFromName, strFirstName, strpart, strLastName;
    
    // Iterate over EmailMessages that are in this trigger and get caseId and EmailFromName.
    for(EmailMessage EM:Trigger.New) {
         
        // Get the CaseId to be associate with the new Contact.
        for (Case c: [SELECT Id, SuppliedName FROM Case  WHERE Id = :EM.ParentId]) {
                    CaseId = c.Id;
            
                    //if the suppliedName exists then prepare to parse out FirstName and LastName, 
                    //otherwise, they will be left blank when inserted into case.
                    if (c.SuppliedName.length() > 0) {
                        EmailFromName = c.SuppliedName;
                    }
                    else {
                        EmailFromName = ' ';
                    }  
                }
        
        //Parse string for FirstName of sender email.
        strFirstName = EmailFromName.substring(0, EmailFromName.indexOf(' '));
        
        //Parse string for LastName of sender email.
        strLastName = EmailFromName.substring(EmailFromName.LastIndexOf(' '), EmailFromName.length());
        
        //Create Contact Record with Info.
        contactList.add(new Contact(FirstName= strFirstName,
               LastName = strLastName,
               Email= EM.FromAddress));
        
        //Save Email for later query.
        ContactEmail = EM.FromAddress;
        
    }
    
    // Try catch statement to catach any errors and report them to the system logs.
    try{    
        
        //Insert the Contact Record into db.
        if (contactList.size() > 0) {
            insert contactList; 
        }
        
        //Loop through the new cases to Update records with New Contact ID.
        for (Case ca : [SELECT Casenumber, ContactId FROM Case WHERE Id = :CaseId]) {
            
            //Loop through the Contact to get the new ContactId to update into the cases.
            for (Contact newContact : [SELECT Email, Id FROM Contact WHERE Email = :ContactEmail]) {
                //Update Case Record with new ContactId.
                ca.ContactId= newContact.Id;
                //ca.Subject = ca.Subject + 'newContactId = ' + newContact.Id;
                caseList.add(ca);
            }
        }
          
        //Update the Case Record into db.
        if (caseList.size() > 0) {
            update caseList;
        }  
     
    // Try catch statement to catach any errors and report them to the system logs.
    }catch(DmlException de ){
        System.debug(de); 
    } 
BALAJI CHBALAJI CH
Hi Stephen,

Please find below the modified code. I have queried the Account record with name 'General Consumer' and associated it with the new inserting contact.
trigger CreateNewContact on EmailMessage (before insert) {
    
    //List and define local vars.
    List<Contact> contactList = new List<Contact>();
    List<Case> caseList = new List<Case>();
    string CaseId, ContactId, ContactEmail, EmailFromName, strFirstName, strpart, strLastName;
    
    //Querying account record whose name is General Consumer
    account ac = [select id, name from account where name =: 'General Consumer' limit 1];
    
    // Iterate over EmailMessages that are in this trigger and get caseId and EmailFromName.
    for(EmailMessage EM:Trigger.New) {
        
        // Get the CaseId to be associate with the new Contact.
        for (Case c: [SELECT Id, SuppliedName FROM Case  WHERE Id = :EM.ParentId]) {
            CaseId = c.Id;
            
            //if the suppliedName exists then prepare to parse out FirstName and LastName, 
            //otherwise, they will be left blank when inserted into case.
            if (c.SuppliedName.length() > 0) {
                EmailFromName = c.SuppliedName;
            }
            else {
                EmailFromName = ' ';
            }  
        }
        
        //Parse string for FirstName of sender email.
        strFirstName = EmailFromName.substring(0, EmailFromName.indexOf(' '));
        
        //Parse string for LastName of sender email.
        strLastName = EmailFromName.substring(EmailFromName.LastIndexOf(' '), EmailFromName.length());
        
        //Create Contact Record with Info. 
        contactList.add(new Contact(FirstName= strFirstName,
                                    LastName = strLastName,
                                    Email= EM.FromAddress,
                                    AccountId = ac.Id)); //Associating Account record Id to the new contact
        
        //Save Email for later query.
        ContactEmail = EM.FromAddress;
        
    }
    
    // Try catch statement to catach any errors and report them to the system logs.
    try{    
        
        //Insert the Contact Record into db.
        if (contactList.size() > 0) {
            insert contactList; 
        }
        
        //Loop through the new cases to Update records with New Contact ID.
        for (Case ca : [SELECT Casenumber, ContactId FROM Case WHERE Id = :CaseId]) {
            
            //Loop through the Contact to get the new ContactId to update into the cases.
            for (Contact newContact : [SELECT Email, Id FROM Contact WHERE Email = :ContactEmail]) {
                //Update Case Record with new ContactId.
                ca.ContactId= newContact.Id;
                //ca.Subject = ca.Subject + 'newContactId = ' + newContact.Id;
                caseList.add(ca);
            }
        }
        
        //Update the Case Record into db.
        if (caseList.size() > 0) 
        {
            update caseList;
        }  
        
        // Try catch statement to catach any errors and report them to the system logs.
    }
    catch(DmlException de )
    {
        System.debug(de); 
    } 
}

Please let me know if that works for you.

Best Regards,
BALAJI
This was selected as the best answer
Stephen02Stephen02
Perfect Balaji. Thank you. 
Stephen02Stephen02
The above BOTH 1) creates a new contact record when an email enters the system AND 2) associates the contact record to an Account called "General Comsumer". 

Would you know how to write the trigger so that it ONLY associates the Contact record with the specific Account record called "General Consumer", assuming the Contact record is not already associated to an account or it is associated to a different account other than "General Consumer" ? (I do not need it to create a new Contact record). 
soni soni 1soni soni 1
@BALAJI CH i have observed that the supplied name you are splitting it can be in different formate
for example : 
in my Gmail, the name is visible as "FirstName LastName"  then in supplied Name i am getting "FirstName LastName" 
but in my Different Email server account it is displaying as "Last Name, First Name" then in supplied Name i am getting "Last Name, First Name"

 
Akash KALGAPUREAkash KALGAPURE
Hi BALAJI CH,

Can you please help me how can we write test class for this Email Message Scenarion to get the code coverage. Can we use case object too wrtite the test class?