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
chriseustacechriseustace 

Sending Mass Email using an apex trigger

Hello all,

I am trying to write a trigger that will send out emails using a template Here is what I have.  I keep getting the "location" variable undefined.  I did use some code I found on this board, but am unsure what "location" is supposed to be:

 

Trigger Code:

 

 trigger SendActivationEmail on Contact (after insert, after update) {

for(Contact cont : trigger.new)
{

if(cont.Send_Activation_Email__c == true)
{

        string message;
        string templateName = 'Thank you for joining Aprigo';
        String[] toAddresses;
        List<Id> idsList = getEmailAddresses(location);
        
        EmailTemplate e = [select Id,Name,Subject,body from EmailTemplate where name like :templateName+'%'];
        
        if(contact.Email != null)
        {
             Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.saveAsActivity = false;
   
            mail.setTargetObjectIds(idsList);
            mail.setTemplateId(e.Id);
           
            mail.setUseSignature(false);
            mail.setSaveAsActivity(false);


            // Send the email
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
        }
        else
        {
            Messaging.SingleEmailMessage mail1 = new Messaging.SingleEmailMessage();
            toAddresses = new String[] {'chris@eustaceconsulting.com'};
            mail1.setToAddresses(toAddresses);
            message = 'This email will sent to you only if Template Not Found!!!';
            mail1.setHtmlBody(message);
        }

    }
        

   }


 


}

 

 

 

 

 

 

Class Code:

 

 public with sharing class MailerUtils
{
    public static List<Id> getEmailAddresses(string groupName)
     {

        List<String> idList = new List<String>();
       
        List<Id> mailToIds = new List<Id>();
       
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = :groupName];
       
        for (GroupMember gm : g.groupMembers) {
       
        idList.add(gm.userOrGroupId);
       
        }
       
        User[] usr = [SELECT Id, email FROM user WHERE id IN :idList];
       
        for(User u : usr) {
       
        mailToIds.add(u.Id);
       
        }
       
        return mailToIds;
                                
}
}

 

 

 

 

Can anyone help?

bob_buzzardbob_buzzard
Looks like the location variable is intended to be the name of a group.  This is often how you'd do mass email - put all the users in a group (e.g. new registration administrators) and then you can change who receives the emails without having to go near the code.
chriseustacechriseustace

Thanks for the reply! 

I actually want to send the email to the contact's email address.  Could anyone assist me with that?

chriseustacechriseustace

Ok, I am close.  My only issue is on line 20, where I am trying to fill the List with email address(es)

 

Here is the code:

 

trigger SendActivationEmail on Contact (after insert, after update) {

for(Contact cont : trigger.new)
{

if(cont.Send_Activation_Email__c == true)
{

        string message;
        string templateName = 'Thank you for joining Aprigo';
        String[] toAddresses;
        //List<Id> idsList = getEmailAddresses(cont.ContactId);
       
        EmailTemplate e = [select Id,Name,Subject,body from EmailTemplate where name like :templateName+'%'];
       
        if(cont.Email != null)
        {
           
        List<Id> mailToIds = new List<Id>();
        mailToIds.add(cont.Email);           
           
             Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.saveAsActivity = false;
  
            mail.setTargetObjectIds(mailToIds);
            mail.setTemplateId(e.Id);
          
            mail.setUseSignature(false);
            mail.setSaveAsActivity(false);


            // Send the email
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
           
            //Update the sent date
           // cont.Activation_Sent_Date__c = now();
            //Increment the # of emails sent
            cont.of_Activation_Emails_Sent__c = cont.of_Activation_Emails_Sent__c + 1;
            //set the "Send Activation Email" checkbox back to No
            cont.Send_Activation_Email__c = false;
           
           
        }
        else
        {
            Messaging.SingleEmailMessage mail1 = new Messaging.SingleEmailMessage();
            toAddresses = new String[] {'chris@eustaceconsulting.com'};
            mail1.setToAddresses(toAddresses);
            message = 'This email will sent to you only if Template Not Found!!!';
            mail1.setHtmlBody(message);
        }

    }
       

   }


 


}

bob_buzzardbob_buzzard
You wouldn't add cont.email into the list, add cont.id instead.  You tell force the ids of the contacts etc you want to mail, and force figures out the email address for you. 
Mark Tyler CrawfordMark Tyler Crawford
It also appears as though you are sending the email message once per loop. This is not bulkified and isn't good practice. It will cause your error message to be sent potentially hundreds of times, quickly filling your inbox. Add the emails to the list<Id> then append them to the final mass message send. You also should move the email template outside of the for each loop as it is only necessary to perform this soql query once. Try something like this: 

trigger SendActivationEmail on Contact (after insert, after update) {

string message;
string templateName = 'Thank you for joining Aprigo';
EmailTemplate e = [select Id,Name,Subject,body from EmailTemplate where name like :templateName+'%'];
Boolean errorFlag = false;

for(Contact cont : trigger.new)
{

if(cont.Send_Activation_Email__c == true)
{

  
        String[] toAddresses;
        
        
        if(cont.Email != null)
        {
            
        List<Id> mailToIds = new List<Id>();
        mailToIds.add(cont.Email);            
            


            //set the "Send Activation Email" checkbox back to No
            cont.Send_Activation_Email__c = false;
            
            
        }
        else
        {
            errorFlag = true;
        }

    } 
        

   }


        Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
        mail.saveAsActivity = false;

        mail.setTargetObjectIds(mailToIds);
        mail.setTemplateId(e.Id);
       
        mail.setUseSignature(false);
        mail.setSaveAsActivity(false);


        // Send the email
        Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
        
        //Update the sent date
       // cont.Activation_Sent_Date__c = now();


       if(errorFlag){
            Messaging.SingleEmailMessage mail1 = new Messaging.SingleEmailMessage();
            toAddresses = new String[] {'chris@eustaceconsulting.com'};
            mail1.setToAddresses(toAddresses);
            message = 'This email will sent to you only if Template Not Found!!!';
            mail1.setHtmlBody(message);
       }
}