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
Josh ThiessenJosh Thiessen 

Email-to-case - Automatically creating a new Person Account?

Does anyone know how to convert the below Apex to be for Person Accounts instead of Contacts?

trigger TriggertoCreateContactformCase on Case (before insert) {
    List<String> UseremailAddresses = new List<String>();
    //First exclude any cases where the contact is set
    for (Case c:Trigger.new) {
        if (c.ContactId==null &&
            c.SuppliedEmail!=''|| c.SuppliedEmail==null)
        {
            UseremailAddresses.add(c.SuppliedEmail);
        }
    }

    //Now we have a nice list of all the email addresses.  Let's query on it and see how many contacts already exist.
    List<Contact> listofallContacts = [Select Id,Email From Contact Where Email in:UseremailAddresses];
    Set<String> ExstingEmails = new Set<String>();
    for (Contact c:listofallContacts) {
        ExstingEmails.add(c.Email);
    }
    
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();

    for (Case c:Trigger.new) {
        if (c.ContactId==null &&
            c.SuppliedName!=null &&
            c.SuppliedEmail!=null &&
            c.SuppliedName!='' &&
           !c.SuppliedName.contains('@') &&
            c.SuppliedEmail!='' &&
           !ExstingEmails.contains(c.SuppliedEmail))
        {
            //The case was created with a null contact
            //Let's make a contact for it
            String[] Emailheader = c.SuppliedName.split(' ',2);
            if (Emailheader.size() == 2)
            {
                Contact conts = new Contact(FirstName=Emailheader[0],
                                            LastName=Emailheader[1],
                                            Email=c.SuppliedEmail
                                            );
                emailToContactMap.put(c.SuppliedEmail,conts);
                casesToUpdate.add(c);
            }
        }
    }
    
    List<Contact> newContacts = emailToContactMap.values();
    insert newContacts;
    
    for (Case c:casesToUpdate) {
        Contact newContact = emailToContactMap.get(c.SuppliedEmail);
        
        c.ContactId = newContact.Id;
    }
}
Saroja MuruganSaroja Murugan

Hi Josh,

Can you please try the below one.
 

And let me know if its works as you excepted.

trigger CaseAutocreateContact on Case (before insert) {
    List<String> emailAddresses = new List<String>();
    //First exclude any cases where the contact is set
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null &&
            caseObj.SuppliedEmail!='')
        {
            emailAddresses.add(caseObj.SuppliedEmail);
            System.Debug('>>> the value of the supplied email is ' + caseObj.SuppliedEmail);
        }
    }
    System.Debug('>>> the size of the email address object is ' + emailAddresses.size());
    
    List<Contact> listContacts = [Select Id,Email From Contact Where Email in :emailAddresses];
    Set<String> takenEmails = new Set<String>();
    for (Contact c:listContacts) {
        takenEmails.add(c.Email);
    }
     
    Map<String,Account> emailToAccountMap= new Map<String,Account>();
    Map<String,Contact> emailToContactMap= new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();
    RecordType personAccountRecordType = [SELECT Id FROM RecordType WHERE Name = 'Customer' and SObjectType = 'Account'];
    for (Case caseObj:Trigger.new) {
            System.Debug('>>> the value of the supplied email is ' + caseObj.SuppliedEmail);
            System.Debug('>>> the value of the first name is ' + caseObj.First_Name__c);
            System.Debug('>>> the value of the last name is ' + caseObj.Last_Name__c );
            System.Debug('>>> the value of the supplied ContactID is ' + caseObj.ContactId);    
        if (caseObj.ContactId==null &&
 caseObj.SuppliedEmail!=null && 
caseObj.Last_Name__c != '' && 
caseObj.Last_Name__c != null && 
caseObj.SuppliedEmail!='' &&
            !takenEmails.contains(caseObj.SuppliedEmail))
        {
            //The case was created with a null contact
            //Let's make a contact for it
           
           Account newPersonAccount = new Account(FirstName= caseObj.First_Name__c,
                                            LastName= caseObj.Last_Name__c,
                                            E_mail_address__c =caseObj.SuppliedEmail,
                                            RecordType=personAccountRecordType );
           
            //emailToAccountMap.put(caseObj.SuppliedEmail,newPersonAccount);
            casesToUpdate.add(caseObj);
         }
    }
    
    List<Account> new Accounts = emailToAccountMap.values();
    insert newAccounts;
    Set<Id> accIds = new Set<Id>();
    for(Account prsnAcc : newAccounts)
    {
        accIds.add(prsnAcc.id);
    }
    Map<String,Account> mapPrsnAccounts = new Map<String,Account>();
    for(Account prsnAcc : [select id,PersonContactId,E_mail_address__c from Account where Id in : accIds])
    {
        mapPrsnAccounts.put(prsnAcc.E_mail_address__c,prsnAcc);
    }

    for (Case caseObj:casesToUpdate) {
        Account newPersonAccount = mapPrsnAccounts.get(caseObj.SuppliedEmail);
        caseObj.AccountId = newPersonAccount.Id;
        System.Debug('>>> the person contact id of the person object is ' + newPersonAccount.PersonContactId);
        caseObj.ContactId = newPersonAccount.PersonContactId;
    }
}

Thanks,
Saroja
Sweet Potato Tec
 

Josh ThiessenJosh Thiessen
I got a string of errors: [cid:image001.png@01D3CB58.C581B910] Josh Thiessen Manager, Customer Experience
Josh ThiessenJosh Thiessen
Errors
Saroja MuruganSaroja Murugan
Hi

Sorry i had posted a wrong coding.

Please try the below one.

trigger TriggertoCreateContactformCase on Case (before insert) {
    List<String> UseremailAddresses = new List<String>();
    //First exclude any cases where the contact is set
    for (Case c:Trigger.new) {
        if (c.ContactId==null &&
            c.SuppliedEmail!=''|| c.SuppliedEmail==null)
        {
            UseremailAddresses.add(c.SuppliedEmail);
        }
    }

    //Now we have a nice list of all the email addresses.  Let's query on it and see how many contacts already exist.
    List<Contact> listofallContacts = [Select Id,Email From Contact Where Email in:UseremailAddresses];
    Set<String> ExstingEmails = new Set<String>();
    for (Contact c:listofallContacts) {
        ExstingEmails.add(c.Email);
    }
    
    Map<String,Account> emailToAccountMap= new Map<String,Account>();
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();
    RecordType personAccountRecordType = [SELECT Id FROM RecordType WHERE Name = 'Customer' and SObjectType = 'Account'];
    for (Case c:Trigger.new) {
        if (c.ContactId==null &&
            c.SuppliedName!=null &&
            c.SuppliedEmail!=null &&
            c.SuppliedName!='' &&
           !c.SuppliedName.contains('@') &&
            c.SuppliedEmail!='' &&
           !ExstingEmails.contains(c.SuppliedEmail))
        {
            //The case was created with a null contact
            //Let's make a contact for it
            String[] Emailheader = c.SuppliedName.split(' ',2);
            if (Emailheader.size() == 2)
            {Account newPersonAccount = new Account(FirstName= caseObj.First_Name__c,
                                            LastName= caseObj.Last_Name__c,
                                            Email_address__c =caseObj.SuppliedEmail,
                                            RecordType=personAccountRecordType );
                //emailToContactMap.put(c.SuppliedEmail,conts);
                casesToUpdate.add(c);
            }
        }
    }
    
    List<Account> newAccounts = emailToAccountMap.values();
    insert newAccounts;
    Set<Id> accIds = new Set<Id>();
    for(Account prsnAcc : newAccounts)
    {
        accIds.add(prsnAcc.id);
    }
    Map<String,Account> mapPrsnAccounts = new Map<String,Account>();
    for(Account prsnAcc : [select id,PersonContactId,Email_address__c from Account where Id in : accIds])
    {
        mapPrsnAccounts.put(prsnAcc.E_mail_address__c,prsnAcc);
    }
    for (Case c:casesToUpdate) {
    Account newPersonAccount = mapPrsnAccounts.get(c.SuppliedEmail);
    c.AccountId = newPersonAccount.Id;
                
        c.ContactId = newPersonAccount.PersonContactId;
    }
}

 
Josh ThiessenJosh Thiessen
It's much better now. There are only 5 errors, but i'm not sure what the problem is. I do have a field for Email Adress on Person accounts in the layout. See image. Also, thank you so much for the help so far.

Errors
Saroja MuruganSaroja Murugan

Can you change the below lines in your code.

Line 36: Account newPersonAccount = new Account(FirstName= c.First_Name__c,
                                            LastName= c.Last_Name__c,
                                            Email_address__c =c.SuppliedEmail,
                                            RecordType=personAccountRecordType );
Line 56: mapPrsnAccounts.put(prsnAcc.Email_address__c,prsnAcc);

Did you have email address field in your account object?

 

Josh ThiessenJosh Thiessen
User-added image

Almost There. I had an error on Line 36 and 37, but all I had to do was add the fields for email address, first name, and last name.

However, I still have an error on line 46 and I'm unsure how to resolve it. 
Saroja MuruganSaroja Murugan
Can you please send the error lines.

Then i will try to solve it.


 
Josh ThiessenJosh Thiessen
Hi Saroja, it's line 46.
Josh ThiessenJosh Thiessen
Missing " at List" is the error
Saroja MuruganSaroja Murugan
Can you please change the line 46 as below

List<Account> newAccounts =new List<Account>();
newAccounts=emailToAccountMap.values();
Jesse MarionJesse Marion
Hi Saroja,

My name is Jesse, I am assisting Josh with trying to figure this apex trigger out.

I have edited the code as you recommended above, and I get a single error at line 46:
    List<Account> newAccounts = newAccounts =new at List<Account>();

Error Missing " at 'List'

Do you know what this is referencing?

Thank you kindly
 
Jesse MarionJesse Marion
Forget to edit out the 'at'

 List<Account> newAccounts = newAccounts =new List<Account>();
Saroja MuruganSaroja Murugan
Hi Jesse,

Im trying to solve this error, but i can't.

Please refer the below link, you got some idea.

https://developer.salesforce.com/forums/?id=906F0000000BSphIAG
 
Jesse MarionJesse Marion
Hi Saroja,

I submitted a support case and they reviewed the code, looks like there was a 3rd } just before line 46 that was causing the error:

    String[] Emailheader = c.SuppliedName.split(' ',2);
            if (Emailheader.size() == 2)
            {Account newPersonAccount = new Account(FirstName= caseObj.First_Name__c,
                                            LastName= caseObj.Last_Name__c,
                                            Email_address__c =caseObj.SuppliedEmail,
                                            RecordType=personAccountRecordType );
                //emailToContactMap.put(c.SuppliedEmail,conts);
                casesToUpdate.add(c);
            }
        }
    }   <------------------------------------------------------------------------------------------------------------------ Issue is this
    
    List<Account> newAccounts = emailToAccountMap.values();
    insert newAccounts;
    Set<Id> accIds = new Set<Id>();
    for(Account prsnAcc : newAccounts)


Correct code should be:

    String[] Emailheader = c.SuppliedName.split(' ',2);
            if (Emailheader.size() == 2)
            {Account newPersonAccount = new Account(FirstName= caseObj.First_Name__c,
                                            LastName= caseObj.Last_Name__c,
                                            Email_address__c =caseObj.SuppliedEmail,
                                            RecordType=personAccountRecordType );
                //emailToContactMap.put(c.SuppliedEmail,conts);
                casesToUpdate.add(c);
            }
        }      
    
    List<Account> newAccounts = emailToAccountMap.values();
    insert newAccounts;
    Set<Id> accIds = new Set<Id>();
    for(Account prsnAcc : newAccounts)


-------------

Now that the code is correct we are wondering if you have any idea on how we can test this in our sandbox, I've tried sending two emails to our sandbox and it does not seem to be registering the cases as I cannot find the emails in the queue nor do I get any bounce backs.

Thanks again
Saroja MuruganSaroja Murugan
Hi,

Email is not received, to your sandbox org. I dont know Why its happened.

Sorry.

Thanks,
Saroja