+ Start a Discussion
Allister McKenzie 10Allister McKenzie 10 

Send email to account team members.

I want to send emails to the account team members when a task is complete and the type is executive call.  I got the user ID from the account team members but am getting errors.  what do I need to fix for this trigger to work.

trigger ExecSponsTrig on Task (after insert, after update) {
    
    List<Messaging.SingleEmailMessage> atm = new List<Messaging.SingleEmailMessage>();  
    EmailTemplate et=[Select id from EmailTemplate where DeveloperName=:'Executive_Sponsor_Call'];
    for(task t : Trigger.new){
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();       
        if(t.Status == 'Completed' && t.Type == 'Executive Call') {
            
            List<AccountTeamMember> recips = new List<AccountTeamMember>(
                [SELECT UserId 
                 FROM AccountTeamMember 
                 WHERE AccountId = :t.AccountId]);
            
            for(AccountTeamMember rid : recips){
                mail.setTargetObjectId(rid.Id);
                mail.setSenderDisplayName('Salesforce System');
                mail.setUseSignature(false);
                mail.setBccSender(false);
                mail.setSaveAsActivity(false);
                mail.setTemplateId(et.Id);
            }
        }
        
        atm.add(mail);
    }
    
    Messaging.sendEmail(atm);
}

I get this error message

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger ExecSponsTrig caused an unexpected exception, contact your administrator: ExecSponsTrig: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_TYPE_FOR_OPERATION, Only Users, Contact or Lead allowed for targetObjectId : 01MM000000CQBLs.: []: Trigger.ExecSponsTrig: line 28, column 1

Best Answer chosen by Allister McKenzie 10
SarfarajSarfaraj
Hi Allister

Replace line 16 of your code,
mail.setTargetObjectId(rid.Id);

by this,
mail.setTargetObjectId(rid.UserId);