Friday, January 24, 2014

Salesforce.com: Send an Email to a list of Contacts Using Javascript

List view in Salesforce can help users accomplish activities in a faster way. You can do a Mass Edit / Update, Mass Transfer records from a list view. As of now, There is no out of the box functionality available to send an email to a list of contacts from Salesforce. (Mass mail is a completely different process. You need to create a separate list view and requires an email template)

Below mentioned code is a simple example in which Javascript is used to copy the email addresses of contacts selected from a list view and puts it into the "TO" box on a new email message.

This functionality can be handy when a user wants to send a simple mail to his contacts. You can optionally tag the activity to any object (Account, Opportunity, Case etc.)


For implementation:

Part I
Go to Setup > Customize > Contacts > Buttons, Links & Actions > New Button or Link
Choose Display Type as List Button & click Display Checkboxes (for Multi-Record Selection)
Behavior > "Execute JavaScript"
Content Source > "OnClick JavaScript"
Paste this code & Click Save

{!REQUIRESCRIPT('/soap/ajax/29.0/connection.js')} 
{!REQUIRESCRIPT('/soap/ajax/29.0/apex.js')} 
try{ 
var arrRecordId = {!GETRECORDIDS( $ObjectType.Contact)}; 
var ret = window.location.pathname+window.location.search; 
var pcEmail = arrRecordId[0]; 
if(arrRecordId.length > 0){ 
var strRecIdList = ''; 
for(var i=0; i < arrRecordId.length; i++){ 
strRecIdList += "'" + arrRecordId[i] + "',"; 

strRecIdList = strRecIdList.substring(0, strRecIdList.length-1); 
var contacts = sforce.connection.query("SELECT Email FROM Contact WHERE Id IN(" + strRecIdList + ")"); 
if(contacts.done == 'true' && parseInt(contacts.size)>0){ 
var cEmail = ''; 
for(var j=0; j < contacts.records.length; j++){ 
if(contacts.records[j].Email != null && contacts.records[j].Email != ''){ 
cEmail += contacts.records[j].Email + "; "; 


cEmail = (cEmail.substring(0, cEmail.length-1)).toString(); 
URL = '/_ui/core/email/author/EmailAuthor?p2_lkid='+pcEmail+'&p24='+cEmail+'&retURL='+ret; 
window.location.href= URL; 



catch(e){ 
alert('An Error has Occurred. \r\nError: ' + e); 
}


Part 2

Go to Setup > Customize > Contacts > Search Layouts
Click Edit next to Contacts List View
Add the new custom button and Save.

Now Click on Contacts Tab and then a list view to an send email.