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
V100V100 

Send Email Help

I am trying to set an apex trigger to send an email template to the account owner once a case has been created.

The email side work ok but i cannot pick up the account owner's email address.

 

Below is the code i have tried, a mix from other sources as i have little salesforce knowledge.

trigger emailToAM on Case (after insert) {
          
for (Case c : trigger.new) {          
    String[] showID = new String[] {c.OwnerId}; 
    List<User> u = [SELECT Id, Name, Email FROM User WHERE Id in :showID];
    String[] toAddresses = new String[] {u.id};  
    
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    // Strings to hold the email addresses to which you are sending the email.  
  
    mail.setToAddresses(toAddresses);
    mail.setReplyTo('noreply@salesforce.com');
    mail.setSenderDisplayName('Call Reception Unit');
    mail.setBccSender(false);
    mail.setUseSignature(false);
    mail.setTargetObjectId(c.ContactId);
    mail.setTemplateId('00XS0000000Ijgl');  
    
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 

I get an error when trying to compile:

Error: Compile Error: Initial term of field expression must be a concrete SObject: LIST:SOBJECT:User at line 6 column 42 

 

Any help much appreciated.

Best Answer chosen by Admin (Salesforce Developers) 
TbomTbom

You should move the user query and emailing code outside of the for loop. Otherwise you run the risks of governor limits with both.

Then collect the User Ids into a Set within the for loop, then outside of for loop go get all found Users into a List or Map and parse for emails. 

Or actually,  you might just be able to add the emails directly by going  toAddresses.add(c.OwnerId__r.email)

 

Hope that helps

All Answers

imuinoimuino
String[] toAddresses = new String[] {u.id};  

 

 The error is in that line, you are trying to acces to a field on u, but u is a list

 

of object not an object itself, what you can do is this

 

String[] toAddresses = new String[] {u[0].id}


Then you are selecting the first SObject on the u list, then you can access its fields



TbomTbom

You should move the user query and emailing code outside of the for loop. Otherwise you run the risks of governor limits with both.

Then collect the User Ids into a Set within the for loop, then outside of for loop go get all found Users into a List or Map and parse for emails. 

Or actually,  you might just be able to add the emails directly by going  toAddresses.add(c.OwnerId__r.email)

 

Hope that helps

This was selected as the best answer
V100V100

Thanks both, got it fixed with your ideas