+ Start a Discussion
Allister McKenzie 10Allister McKenzie 10 

Lookup fields are null in email

I am writing at trigger that sends an email to account team members whenever a task is completed.  The task description field shows up in the email but the Assigned to and Related to fields are null.  How can I get these fields to show in the email.

trigger MyCoolTrigger on Task (after insert, after update) {

	List<Messaging.SingleEmailMessage> atm = new List<Messaging.SingleEmailMessage>();  
    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]);

            String body = 'Executive Sponsor:  ' + t.Owner;
            body += '<br/><br/>';
            body += 'Account:  ' + t.What;
            body += '<br/><br/>';
            body += 'Description:<br/> ' + t.Description;  

            mail.setSenderDisplayName('Salesforce System');
            mail.setUseSignature(false);
            mail.setBccSender(false);
            mail.setSaveAsActivity(false);
            mail.setHtmlBody(body);
            
            for(AccountTeamMember rid : recips){
                mail.setTargetObjectId(rid.UserId);
            }
        }
        
        atm.add(mail);
    }
    
    Messaging.sendEmail(atm);
}


Best Answer chosen by Allister McKenzie 10
SonamSonam (Salesforce Developers) 
If the value of the WhatIdfield is any other object, and the value of the WhoId field is a Contact object, then Salesforce uses that contact’s AccountId.

Otherwise, Salesforce sets the value of the AccountId field to null.

At the time of creation of a task, are you giving the Name on the task as a Contact?