Friday, November 28, 2014

Salesforce - Mass email Contacts using Visualforce email template

Today, we will illustrate how you can send up to 1000 emails to contacts using a Visualforce email template. 

1. Create Visualforce email template in your Salesforce.com instance:
    Go to Setup < Communication Templates < Email Templates and click "New Template"

2. Select Visualforce.

 3. Enter Required information and chose Contact as your "Recipient" and "Related To" types.

4. Edit your template.

5. Now, you have different options to leverage this email template.

  • Create a custom Visualforce page, and a custom controller that you will use as a list button in the Contact tab.
  • Write a script and run it through Execute Anonymous in Eclipse or the Developer Console.

Today, we will be using the latter option:

We will create a list with contacts that we will send the emails to (max. 1000). Then we will create a batch of emails. After that we will send the emails to the recipients.

// List that will store emails that will be sent
List allMails = new List(); 

// list of contacts
List contacts = [Select id, Email, LastName from Contact Limit:1000]; 

// Email Template
EmailTemplate myEMailTemplate = [Select id from EmailTemplate where Name =: 'Test Template']; 

// emails are being created and stored in list
for(Contact c: contacts){ 
   
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setTemplateId(myEMailTemplate.id);
email.setTargetObjectId(c.id); 
email.setSenderDisplayName('Sender Display Name'); 
    allMails.add(email);
 }

// send emails, false makes sure that the method will not stop when an error occurred, such as a bounced email
Messaging.sendEmail(allMails, false); 

No comments:

Post a Comment