function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Julio SJulio S 

Send an email to an external email address when a task is created with specific subject

Hi Devs,

Is it possible to send a notification to a user, or to an external email address when there is a task created on a contact record with a specific subject (Task subject). Please advise, Im quite noob on coding with apex.

Thanksm
Julio
Best Answer chosen by Julio S
Abdul KhatriAbdul Khatri
First you need a trigger that will call the email functionality based on the scenarion

 Trigger
trigger SendEmailNotification on Task (after insert) {

	Set<Id> idContactSet = new Set<Id>();
    EmailManager emailMgr = new EmailManager();
    
    for(Task task : trigger.new) {
        
        if(task.WhoId.getsobjectType != Schema.SObjectType.Contact) continue;
        
        if(task.Subject != 'specific') return
        
        idContactSet.add(task.WhoId);
    }
    
    if(idContactSet.isEmpty()) return;
    
    List<Contact> contactList = [SELECT Id, Email FROM Contact WHERE Id IN :idContactSet];
    
    for(Contact contact :contactList) {
        
        emailMgr.sendMail (contact.Email, task, '' );
    }
    
}

Here is the class to send an EmailManager
public class {

    // Public method
    public void sendMail(String address, String subject, String body) {
        // Create an email message object
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {address};
        mail.setToAddresses(toAddresses);
        mail.setSubject(subject);
        mail.setPlainTextBody(body);
        // Pass this email message to the built-in sendEmail method 
        // of the Messaging class
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
        
        // Call a helper method to inspect the returned results
        inspectResults(results);
    }
    
    // Helper method
    private static Boolean inspectResults(Messaging.SendEmailResult[] results) {
        Boolean sendResult = true;
        
        // sendEmail returns an array of result objects.
        // Iterate through the list to inspect results. 
        // In this class, the methods send only one email, 
        // so we should have only one result.
        for (Messaging.SendEmailResult res : results) {
            if (res.isSuccess()) {
                System.debug('Email sent successfully');
            }
            else {
                sendResult = false;
                System.debug('The following errors occurred: ' + res.getErrors());                 
            }
        }
        
        return sendResult;
    }

}

 

All Answers

Abdul KhatriAbdul Khatri
First you need a trigger that will call the email functionality based on the scenarion

 Trigger
trigger SendEmailNotification on Task (after insert) {

	Set<Id> idContactSet = new Set<Id>();
    EmailManager emailMgr = new EmailManager();
    
    for(Task task : trigger.new) {
        
        if(task.WhoId.getsobjectType != Schema.SObjectType.Contact) continue;
        
        if(task.Subject != 'specific') return
        
        idContactSet.add(task.WhoId);
    }
    
    if(idContactSet.isEmpty()) return;
    
    List<Contact> contactList = [SELECT Id, Email FROM Contact WHERE Id IN :idContactSet];
    
    for(Contact contact :contactList) {
        
        emailMgr.sendMail (contact.Email, task, '' );
    }
    
}

Here is the class to send an EmailManager
public class {

    // Public method
    public void sendMail(String address, String subject, String body) {
        // Create an email message object
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {address};
        mail.setToAddresses(toAddresses);
        mail.setSubject(subject);
        mail.setPlainTextBody(body);
        // Pass this email message to the built-in sendEmail method 
        // of the Messaging class
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
        
        // Call a helper method to inspect the returned results
        inspectResults(results);
    }
    
    // Helper method
    private static Boolean inspectResults(Messaging.SendEmailResult[] results) {
        Boolean sendResult = true;
        
        // sendEmail returns an array of result objects.
        // Iterate through the list to inspect results. 
        // In this class, the methods send only one email, 
        // so we should have only one result.
        for (Messaging.SendEmailResult res : results) {
            if (res.isSuccess()) {
                System.debug('Email sent successfully');
            }
            else {
                sendResult = false;
                System.debug('The following errors occurred: ' + res.getErrors());                 
            }
        }
        
        return sendResult;
    }

}

 
This was selected as the best answer
Abdul KhatriAbdul Khatri
Hey Was this helpful?
Abdul KhatriAbdul Khatri
Please let me know if was able to help you with
Julio SJulio S
Thanks for all the tips devs, I'll give it a a shot today as I am out of the office for a couple of days. 
Julio SJulio S
@Abdul Im getting this error mate
Error: Compile Error: A non foreign key field cannot be referenced in a path expression: WhoId at line 5 column 17
Julio SJulio S
@Abdul and for the Apex Class I am getting this error.

Error: Compile Error: Unexpected token '{'. at line 1 column 14
Julio SJulio S
@Abdul Please see the images. Thanks for the assistance
User-added image
User-added image
Abdul KhatriAbdul Khatri
I miss the classname for the Email class. Try this code and give me your update.
public class EmailManager {

    // Public method
    public void sendMail(String address, String subject, String body) {
        // Create an email message object
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {address};
        mail.setToAddresses(toAddresses);
        mail.setSubject(subject);
        mail.setPlainTextBody(body);
        // Pass this email message to the built-in sendEmail method 
        // of the Messaging class
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
        
        // Call a helper method to inspect the returned results
        inspectResults(results);
    }
    
    // Helper method
    private static Boolean inspectResults(Messaging.SendEmailResult[] results) {
        Boolean sendResult = true;
        
        // sendEmail returns an array of result objects.
        // Iterate through the list to inspect results. 
        // In this class, the methods send only one email, 
        // so we should have only one result.
        for (Messaging.SendEmailResult res : results) {
            if (res.isSuccess()) {
                System.debug('Email sent successfully');
            }
            else {
                sendResult = false;
                System.debug('The following errors occurred: ' + res.getErrors());                 
            }
        }
        
        return sendResult;
    }

}

 
Julio SJulio S
Thanks Abdul, how about the trigger? Im still getting this error.
User-added image
Abdul KhatriAbdul Khatri
Use this
trigger SendEmailNotification on Task (after insert) {

	Set<Id> idContactSet = new Set<Id>();
    EmailManager emailMgr = new EmailManager();
    
    for(Task task : trigger.new) {
        
        if(task.WhoId.getSObjectType() != Schema.Contact.SObjectType) continue;
        
        if(task.Subject != 'specific') return
        
        idContactSet.add(task.WhoId);
    }
    
    if(idContactSet.isEmpty()) return;
    
    List<Contact> contactList = [SELECT Id, Email FROM Contact WHERE Id IN :idContactSet];
    
    for(Contact contact :contactList) {
        
        emailMgr.sendMail (contact.Email, task, '' );
    }
    
}

 
Julio SJulio S
Hi Abdul, thanks for being so patient, I am now getting this new error
User-added image
Abdul KhatriAbdul Khatri
That is just a string missed the single quote. Here is with correction
 
trigger SendEmailNotification on Task (after insert) {

	Set<Id> idContactSet = new Set<Id>();
    EmailManager emailMgr = new EmailManager();
    
    for(Task task : trigger.new) {
        
        if(task.WhoId.getSObjectType() != Schema.Contact.SObjectType) continue;
        
        if(task.Subject != 'specific') return
        
        idContactSet.add(task.WhoId);
    }
    
    if(idContactSet.isEmpty()) return;
    
    List<Contact> contactList = [SELECT Id, Email FROM Contact WHERE Id IN :idContactSet];
    
    for(Contact contact :contactList) {
        
        emailMgr.sendMail (contact.Email, 'Submitted form - Talk to an Expert', '' );
    }
    
}

 
Julio SJulio S
Hi Abdul, users are now getting this error when they create task 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger SendEmailNotification caused an unexpected exception, contact your administrator: SendEmailNotification: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.: []: Class.SomeClass.sendMail: line 13, column 1​




public class SomeClass {

    // Public method
    public void sendMail(String address, String subject, String body) {
        // Create an email message object
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {address};
        mail.setToAddresses(toAddresses);
        mail.setSubject(subject);
        mail.setPlainTextBody(body);
        // Pass this email message to the built-in sendEmail method
        // of the Messaging class
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
        // Call a helper method to inspect the returned results
        inspectResults(results);
    }
    // Helper method
    private static Boolean inspectResults(Messaging.SendEmailResult[] results) {
        Boolean sendResult = true;
        // sendEmail returns an array of result objects.
        // Iterate through the list to inspect results.
        // In this class, the methods send only one email,
        // so we should have only one result.
        for (Messaging.SendEmailResult res : results) {
            if (res.isSuccess()) {
                System.debug('Email sent successfully');
            }
            else {
                sendResult = false;
                System.debug('The following errors occurred: ' + res.getErrors());                
            }
        }
        return sendResult;
    }
}
Abdul KhatriAbdul Khatri
Can you please verify your Email Deliverability Settings is set to "All Emails" instead "No Access"

User-added image
Julio SJulio S
All working now mates! thanks Abdul