+ Start a Discussion
Bob_zBob_z 

Apex trigger Send an email to a user when their activity is completed by the asssign to person

I am trying to create a trigger that will fire off a email to a user when the assign to person completes their activity.

 

how do i add a email template to this trigger below?

 

trigger Trigger_Request_CompletedAfterInsertAfterUpdate on Task (after insert, after update)
 {
    
 
   Task[] completedTasks = Trigger.new;
   for(Task t : completedTasks){
      if(t.RecordTypeId == '01270000000UGMe' && t.Status=='Completed'){
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
      }
   }
}

 

Shashikant SharmaShashikant Sharma

You can not assign Email template to mail but you can query email template like this

 

EmailTemplate emailTemp = [Select Body, Subject  from EmailTemplate where Name = 'MyEmailTemplate'];

See this for more what you can fetch

http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_emailtemplate.htm#topic-title

 

and use it like

 

mail.subject = emailTemp.Subject

mail.setPlainTextBody = emailTemp.body;

 

See this what you can set in mail

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_single.htm

 

 

David81David81

Is there a reason for not using a Workflow Rule and Email Update to do this?

Bob_zBob_z

Salesforce will not let you send email through a activity workflow.

David81David81

Well, I learned something new today. Having never tried it, I guess I just assumed you could, sorry :)

Bob_zBob_z

I tried this code below, but i am not receiving an email. I would rather have the email go to the user who created the activity, but i'm not sure how to do that.

 

trigger Trigger_Request_CompletedAfterInsertAfterUpdate on Task (after insert, after update)
 {
    
 
   Task[] completedTasks = Trigger.new;
   for(Task t : completedTasks){
      if(t.RecordTypeId == '01270000000UGMe' && t.Status=='Completed'){
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();      

    mail.setToAddresses(new String[] {'bpoliquin@cybexintl.com'});          

    mail.setSubject('Testing Trigger');        

    mail.setPlainTextBody('This is a test for trigger');
        
      }
   }
}

Shashikant SharmaShashikant Sharma

Just remove this 

t.RecordTypeId == '01270000000UGMe' && t.Status=='Completed' condition and then check do you recieve email.

Bob_zBob_z

Okay I updated my code to actually send the email, and it works.

 

now i need to send it to the user who created the activity.

 

trigger Trigger_Request_CompletedAfterInsertAfterUpdate on Task (after insert, after update)
 {
    
 
   Task[] completedTasks = Trigger.new;
   for(Task t : completedTasks){
      if(t.RecordTypeId == '01270000000UGMe' && t.Status=='Completed'){
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();      

    mail.setToAddresses(new String[] {'bpoliquin@cybexintl.com'});          

    mail.setSubject('Testing Trigger');        

    mail.setPlainTextBody('This is a test for trigger');
    mail.saveAsActivity = false;
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
      }
   }
}

David81David81

One thing you'll want to do is create a list of emails to send once you've looped through your Tasks.

 

List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

//loop through your tasks and after constructing each email add...

emails.add(email);


//then pass that list to your send method

 

 

 Also, if you want to send to the Task creator, you can use:

mail.setTargetObjectId(t.CreatedById);

 

Bob_zBob_z

Thank you all for helping, the trigger is woeking great, now I need to write the test for this trigger.

Shashikant SharmaShashikant Sharma

Just share the exact working copy of your trigger , it will be heilful for wrting test class for it.

Bob_zBob_z

trigger

Trigger_Request_CompletedAfterInsertAfterUpdate onTask (afterinsert, afterupdate)

{

 

 

  

Task[] completedTasks = Trigger.new;

  

for(Task t : completedTasks){

  

   List<Messaging.SingleEmailMessage> mails =

new List<Messaging.SingleEmailMessage>();

 


 

 

     

if(t.RecordTypeId == '01270000000UGMe' && t.Status=='Completed'){

         Messaging.SingleEmailMessage mail =

new Messaging.SingleEmailMessage();

         mails.add(mail);      

 

    mail.setTargetObjectId(t.CreatedById);          

mail.setSubject(

'Your requesting has been completed');        

mail.setPlainTextBody( t.Activity_Comment__c);

    mail.saveAsActivity =

false;

   

Messaging.sendEmail(

new Messaging.SingleEmailMessage[] { mail });

        

      }

   }

}

Shashikant SharmaShashikant Sharma

Try this for test class

@istest
private class taskSendMailTestClass{

    private static testmethod void taskSendMailTest()
    {
        Account a = new Account(Name = 'Test' , Manager__c = UserInfo.getUserId());
        insert a;
        
        
        Task t = new Task(whatid = a.id , ownerid = UserInfo.getUserId() , RecordTypeId = '01270000000UGMe' );
        insert t;
        
        t.Status=='Completed
        update t;
    }



}

 

David81David81

I hope you don't mind, but I cleaned up the code on that trigger a bit. The location of the list and such just didn't seem right...

 

trigger Trigger_Request_CompletedAfterInsertAfterUpdate onTask (afterinsert, afterupdate){

    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
   
    for(Task t : Trigger.new){

        if(t.RecordTypeId == '01270000000UGMe' && t.Status=='Completed'){

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

            mail.setTargetObjectId(t.CreatedById);         

            mail.setSubject('Your requesting has been completed');       

            mail.setPlainTextBody(t.Activity_Comment__c);

            mail.saveAsActivity = false;

            mails.add(mail);  

        }

    }
    if(!mails.isEmpty(){
        Messaging.sendEmail(mails);
    }

}
David81David81

Not sure why there is an Account included in that test class. Perhaps you could get away with...

 

@istest
private class test_Request_Completed_Trigger{

    private static testmethod void taskSendMailTest(){
       
        Task t = new Task(ownerid = UserInfo.getUserId() , RecordTypeId = '01270000000UGMe' );
        t.Status = 'Completed';
        t.Activity_Comment__c = 'some comment';
        insert t;

    }



}

 

Shashikant SharmaShashikant Sharma

Yes I know no need for Account just used it for whatid , that is not required , jsut used it because usualy task has whoid or what id but I know it is not a required field. 

faceroy123faceroy123

Hey,

 

Thanks for this. Is there a way to modify this to send the email to the manager of the person who owns the task?

 

Thank you.

kweikwei

Mr. Sharma,

 

Thanks for the information about fetching data from email templates:

 

I tried it out, and it works. However, I am wondering if it is possible to have fields embedded in the message be rendered in the message output.

 

For example, my email template contains the following expression:

{!Review__c.Commentor__c.First_Name__c},

 

And I would like that expression to be evaluated before being sent to the recipient. Is there any way to make this work?

PFangPFang

This piece of code just kept me from being shouted at, everyone's been complaining bout being spammed during my trial run. 

 

 

mail.setTargetObjectId(t.CreatedById);

 I have been using this for so long and merely got emails redirected.

 

String[] toAddresses = new String[] {}

 David81, you are a coding god!

JFowlerJFowler
I'm a little late here, but running into an unexpected token error for '}' on if(!mails.isEmpty(){  in the code below. Can someone 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);
    
    }
    
}