Case that I`m struggling with for some time now:

Salesforce org with email-to-case enabled. Few queues created and assignment rules for each queue (that is, if email comes to [email protected] then case is assigned to Queue with name "queue1"). Works fine.

What needs to be added is a check -> if Case comes in and there is account with relevant e-mail address in Contacts, case should be assigned to that user.

Examples: 1) There is an account with Contact "[email protected]" and account owner is user Y . Case comes from [email protected] to [email protected] . Case should be assigned to user Y.

2) There is no such contact with email "[email protected]". Case comes from [email protected] to [email protected]. Case should be assigned to Queue "queue1"

Currently I have tried to achieve this using Process Builder or Trigger.Works fine with 1st case (when there is a contact in the system) and fails for 2nd case (when there is no such contact in the system).

What could be the ways to achieve this functionality and why the trigger below fails?

trigger CaseOwner on Case (after update) {

  Set<Id> AccountIds = new Set<Id>();    
  for (Case cs: Trigger.new) {
     if (cs.AccountId != null) {

  Map<Id, Account> accountEntries = new Map<Id, Account>(
    [select Id,Name, Sales_responsible__c from Account where id in :AccountIds]

  for (Case caseRec : Trigger.new) {   

     if (accountEntries.get(caseRec.AccountId).Sales_responsible__c != null) {
        String salesRep= accountEntries.get(caseRec.AccountId).Sales_responsible__c; 
        System.Debug('Sales responsible is ' + salesRep);

        caseRec.OwnerId= salesRep;


Trigger fails with an error message:

CaseOwner: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.CaseOwner: line 16, column 1

2 Answers 2


A reason this may be failing is that email to Case will not always assign an Account or Contact to a Case. Hence Case.AccountId and Case.ContactId can be null. This happens when SFDC can't find a Contact with a matching email address or, I think, if there are multiple Contacts with the same email address).

So, the latter portion of your trigger should be:

for (Case cs: Trigger.new) {   

 if (accountEntries.containsKey(cs.AccountId) && 
     accountEntries.get(cs.AccountId).Sales_responsible__c != null) {
     String salesRep= accountEntries.get(cs.AccountId).Sales_responsible__c; 
     System.Debug('Sales responsible is ' + salesRep);

    cs.OwnerId= salesRep;

Hi @Juris Upenieks in Salesforce there is a Exception however, for Cases (Standard Object). Case Records can be assigned to Queues.like tasks cannot be assigned to Queues.

I'm sharing a link may be it works for you.


You must log in to answer this question.

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