If we assign a task to someone else, we can get an automated notice when the task is completed.
For that i have written one trigger mentioned below that trigger is working fine but email is being sent to creator(When a Task is created, assigned and completed by same person, still an email is being sent to creator). but i don't want like that.could any one please help me this issue
Please find the below trigger and correct me.
trigger TaskEmailNotification on Task (before update ) {
Set<Id> ownerIds = new Set<Id>();
for(Task tsk: Trigger.New){
if(tsk.Status=='Completed' && Trigger.oldMap.get(tsk.Id).Status != 'Completed'){
ownerIds.add(tsk.CreatedById);
}
}
// Build a map of all users who are assigned the tasks
Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :ownerIds]);
List<Messaging.SingleEmailMessage> emailMsglist=new List<Messaging.SingleEmailMessage>();
for(Task tsk : Trigger.New) {
if(tsk.Status=='Completed' && Trigger.oldMap.get(tsk.Id).Status != 'Completed'){
User theUser = userMap.get(tsk.CreatedById);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {theUser.Email};
mail.setToAddresses(toAddresses); // Set the TO addresses
mail.setSubject('A task has been updated'); // Set the subject
// Next, create a string template. Specify {0}, {1} etc. in place of actual values.
String template = 'Hello {0}, \nYour task has been Completed. Here are the details - \n\n';
template+= 'Subject -'+tsk.Subject+' \n';
template+= 'Status - '+tsk.Status +' \n';
template+= 'Priority - '+tsk.Priority +' \n';
List<String> args = new List<String>();
args.add(theUser.Name);
// Here's the String.format()
String formattedHtml = String.format(template, args);
mail.setPlainTextBody(formattedHtml);
emailMsglist.add(mail);
}
}
Messaging.SendEmail(emailMsglist);
}
Edit 1
But i have one more question on the same trigger.Can you please help me on that Issue.Please find below is the my Question. Question is: Task Email content does not reference to actual task.I got below email, which looks to be not correct:
-----Original Message----- From: ABC (ABC Connections) Sent: Friday, April 29, 2016 4:42 PM To: ABC (ABC Connections) (ABC Connections) Subject: A task has been updated Hello ABC, Your task has been Completed. Here are the details - Subject -Test of Auto Email Status - Completed Priority - Normal This should have been followed standard template like below To: Surya Dash EFG has updated the following new task: Subject: Test of Auto Email Opportunity: test11 Status - Completed Priority: Normal For more details, click the following link: my.salesforce.com/012C0000000QV4K
Edit 2
Hi Team, I have one more issue on this same Trigger ,That is how we need to restrict the email notifications to only those tasks created by the specific roles/profiles .