+ Start a Discussion
JFowlerJFowler 

Trouble with Trigger to Send Email off of Closed Task

I'm working on a trigger that will send an email to the user who created a task when the task is closed by a user other than the one that created it, and am running into some trouble with the code. I'm getting an unexpected token error (unexpected token: '{') on this piece: if(!mails.isEmpty(){

Can someone possibly help out with what might be going wrong? Also, do you know how I can limit this to be only being tasks assocaited to my custom object, Closing__c? Thanks for your help!

trigger Task_Email_Trigger on Task (after insert, after update){
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>(); 
    
    for(Task t : Trigger.new){
        if(t.CreatedById != t.OwnerId && t.Status == 'Completed'){
            
            EmailTemplate et=[Select id from EmailTemplate where DeveloperName='Task_Complete_Template'];
            mail.setTemplateID(et.Id);
            mail.setTargetObjectID(t.CreatedById);
            mail.saveAsActivity = false;
            Messaging.SingleEmailMessage = new Messaging.SingleEmailMessage();
            
            mails.add(mail); 
             
        }
        
    }
    if(!mails.isEmpty(){
        Messaging.sendEmail(mails);
    
    }
    
}
surasura

your if statement is not closed as it should be  like this  if(!mails.isEmpty()) {   }  it need another extra ' )'
ManojjenaManojjena
HI Jacob,

Try with below code .It will help I have removed the template query from loop .
 
trigger Task_Email_Trigger on Task (after insert, after update){
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>(); 
	id templateId=[Select id from EmailTemplate where DeveloperName='Task_Complete_Template'].Id;
    for(Task t : Trigger.new){
        if(t.CreatedById != t.OwnerId && t.Status == 'Completed'){
			Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
             mail.setTemplateID(templateId);
            mail.setTargetObjectID(t.CreatedById);
            mail.saveAsActivity = false;
            mails.add(mail); 
        }
    }
    if(!mails.isEmpty()){
        Messaging.sendEmail(mails);
    }
}

Let me know incase any doubt .

Thnaks 
Manoj
JFowlerJFowler
Manoj, 
Thank you, that seems to help. One question:
How do I make this work only when the task is realted to my custom closing object? 
 
JFowlerJFowler
Manoj, 

It seems this now works. One thing is I built merge fields into the template, but they aren't being pulled in when it sends from the trigger. Do you know how I can make sure these are included? The merge fields are below: 
An assigned task has been marked as completed. 
{!Task.Subject} 
{!Task.Link} 
{!Task.What}