Develop custom button using APEX for mass email directly from a list view possible? - Answers - Salesforce Trailblazer Community
Trailblazer Community
Ask Search:
Pierre MassenetPierre Massenet 

Develop custom button using APEX for mass email directly from a list view possible?

Hi, 

I would to create a button "Mass Email" that will allow to mass email all contacts that are in list view. 

I know I could use the Mass Email button down of the contact page and then create the same list view and email them.. but this is double work. 
I created all the views that I need, so now I would like to just go and use them to email my contacts! 

Any suggestion?

Pierre
Best Answer chosen by Pierre Massenet
Deepak AnandDeepak Anand
Well, I have just done something for you. Check this: https://gist.github.com/anonymous/6991194

What does appendTags() do ?
(i) Appends the Link Tag (Link to jQuery UI Stylesheet) to the Head tag of the Page.
(ii) Appends a DIV Tag (that would form the jQuery Modal Dialog) to the Body tag of the Page.

What does createPopupWindow() do ?
Create a jQuery Modal Dialog with buttons 'Send Mail' and 'Cancel'.

What does fetchEmailTemplates() do ?
Its queries the Database and fetches all the Email Templates. It then enumerates them to a Drop-Down list(represented in HTML as <select id="email-template" style="width:380px"></select>).

What does sendMail() do ?
Its does the Mail sending part. It will use the Template Id that was selected from the Drop-Down list and the Contact Ids that you had selected from the List View as the Recipients. The sendMail() will be invoked on clicking the Send Mail button. This button will only work if you had selected at least 1 Contact and also selected the Template Id.

Now, you will have to create a List Button for Contacts. Follow this: 
  1. http://www.salesforce.com/us/developer/docs/fundamentals/Content/adg_composite_app_create_custom_list_button_try_it_out.htm
  2. http://help.salesforce.com/HTViewHelpDoc?id=defining_custom_links.htm&language=en_US (http://help.salesforce.com/HTViewHelpDoc?id=defining_custom_links.htm&language=en_US)
You will have something kinda this:
User-added image

All Answers

Bill GreenhawBill Greenhaw
You can do Mass Email using Apex. Here is a tutorial - http://www.mindfiresolutions.com/Sending-Mass-Email-through-Apex-Controllers-2344.php (http://www.mindfiresolutions.com/Sending-Mass-Email-through-Apex-Controllers-2344.php" target="_blank)

Here is a page that goes into Apex and email handling - http://wiki.developerforce.com/page/An_Introduction_To_Email_Services_on_Force.com (http://wiki.developerforce.com/page/An_Introduction_To_Email_Services_on_Force.com" target="_blank)
Deepak AnandDeepak Anand
+1 @[Bill Greenhaw]. I have seen this question coming up on the Community ocassionaly. So, I feel that urges for a Button trick!

Well, if you really love to see something similar, then I could think of something like this: "When you click on this button and then a small pop-up window jumps in and then you could select the Email Template and click Send." So this is not similar to the native Mass Mail User Interface but uses the in-built Mass Mail functionality behind the scenes and it is again a matter of saving clicks and you will never want to go thro' that wizard-like steps again! You won't need to write APEX or have Visualforce but just some JavaScript. Hang-on until tomorrow(its late here User-added image ) and lemme see what I can come up with! 
Bill GreenhawBill Greenhaw
That would be awesome Deepak.
Pierre MassenetPierre Massenet
I am looking forward to testing this Deepak!!


Thanks Bill, I will try first to understand all this ( I am a begginner!!)

Pierre
David LiuDavid Liu
Two of the best in the business helping you out - you are very lucky Pierre!

Btw - if you're looking to get started on Apex coding, this site is aimed at you!
www.sfdc99.com

Hope this helps!
David
Deepak AnandDeepak Anand
Well, I have just done something for you. Check this: https://gist.github.com/anonymous/6991194

What does appendTags() do ?
(i) Appends the Link Tag (Link to jQuery UI Stylesheet) to the Head tag of the Page.
(ii) Appends a DIV Tag (that would form the jQuery Modal Dialog) to the Body tag of the Page.

What does createPopupWindow() do ?
Create a jQuery Modal Dialog with buttons 'Send Mail' and 'Cancel'.

What does fetchEmailTemplates() do ?
Its queries the Database and fetches all the Email Templates. It then enumerates them to a Drop-Down list(represented in HTML as <select id="email-template" style="width:380px"></select>).

What does sendMail() do ?
Its does the Mail sending part. It will use the Template Id that was selected from the Drop-Down list and the Contact Ids that you had selected from the List View as the Recipients. The sendMail() will be invoked on clicking the Send Mail button. This button will only work if you had selected at least 1 Contact and also selected the Template Id.

Now, you will have to create a List Button for Contacts. Follow this: 
  1. http://www.salesforce.com/us/developer/docs/fundamentals/Content/adg_composite_app_create_custom_list_button_try_it_out.htm
  2. http://help.salesforce.com/HTViewHelpDoc?id=defining_custom_links.htm&language=en_US (http://help.salesforce.com/HTViewHelpDoc?id=defining_custom_links.htm&language=en_US)
You will have something kinda this:
User-added image

This was selected as the best answer
Pierre MassenetPierre Massenet
Hello,

Thanks for this great reply!
I am out of the office and can try to set it up, but I will let you know next week how it works for me. Seems amazing though!!

Pierre
Conrad JoosteConrad Jooste
Hi @Deepak - thanks very mush for this - Everything seems to work as described above up to the point of sending BUT I haven't reveiced any of my test emails??

Any ideas?
Send email issue

I am using Chrome & get the final message saying that emails have been sent (see attached).

Thanks
Conrad
Deepak AnandDeepak Anand
So, as I have mentioned in the previous posts, this is not an out-of-the-box functionality. It still uses the Mass Mail feature.

I would suggest you to look into - Your Name | My Settings | Email | Mass Emails to see the status.

User-added image
Conrad JoosteConrad Jooste
Yes, there's nothing under my mass emails. So not sure how else to troubleshoot?
Naman BawaNaman Bawa
I am getting the error message "User-added image
Deepak AnandDeepak Anand
User-added image! How can I be so careless!

I guess the reason, it didn't work for @Conrad too!

Well, please include this line too:

{!REQUIRESCRIPT('/soap/ajax/28.0/connection.js')} as the first line!
Conrad JoosteConrad Jooste
Ahhh, beautiful! It now works! THANKS very much @Deepak.

I assume this would work for leads but I would just need to switch out the contacts v leads references?

Is there a simple way to have the templates list in alphabetical order and/or the folder structure for the communication templates displayed?
Conrad JoosteConrad Jooste
& another potential enhancement would be to only show Available For Use templates. :-)
Deepak AnandDeepak Anand
Excellent! I am so glad. It did help someone :)

I will work them out soon and post the code! Also, I apprehend, about Folders and things like that since it could overload the button, but lemme see what I can do.

Gosh! I am badly gettin addicted to these buttons now.
Conrad JoosteConrad Jooste
Awesome - thanks Deepak!
Manisha PatilManisha Patil
Hi, I am not getting the popup. Am I missing anything?
Manisha PatilManisha Patil
got it ! it working now. Awesome feature.. Thank you very much
Conrad JoosteConrad Jooste
Hi Deepak, have you managed to look at this again to order the templates (A-Z) & only show 'available for use' ones?
Thanks
Deepak AnandDeepak Anand
Hey Conrad,

I am glad that you are still using this!

Can you try this: https://gist.github.com/anonymous/7d825037ff63ea607f8f

Best,
Deepak
Conrad JoosteConrad Jooste
Deepak, I assume this is updated code, yes?
Spencer EsseySpencer Essey
Thank You Deepak, 

This is a great button and truly useful!
Eytan KiselstainEytan Kiselstain
Thank you Deepak! This is fantastic and very useful!
I'm looking for a similar button - from a list of contacts, choose severals and send a specific email template based on each one details, to one, different contact. Could you help with that? Thanks in advance!
Josh HarshJosh Harsh
Would is be possible to use this on a Custom Object as well?
Marcel HobizalMarcel Hobizal
OMG!  Deepak is the most amazing person out there!!!!   Just put this in my sandbox to try.  So cool!  

Does this work on Custom Objects?  
Deepak AnandDeepak Anand
Oh! Thank you all. I am not sure but I'll have to try it out.
Bill GreenhawBill Greenhaw
I have to agree. Deepak is the man!
Marcel HobizalMarcel Hobizal
@Deepak, I tried changing the reference in your code to the Custom Object name.  Everything worked except for sending of the mass email.  Any ideas? 
Jeff SummersJeff Summers
Hi All.  This solution looks great.  However, I was curious if it allows you to have an "Email Preview" screen to appear?  Also, more importantly, does the email in question show up under every contacts/users Activity History?
Nikilesh KopparthiNikilesh Kopparthi
Hello Deepak!
I am using this piece of code for an app I am developing, and it works perfectly. The only issue I have is that I want to show templates only part of a specific folder in the drop down. I tried adding "AND FolderId = '0014812348******' to the query in the fetchemailtemplatefunction but I keep getting "Unexpected token ILLEGAL" error. Can you please help!
Thanks!!
Devon SacksDevon Sacks
You could always just use the following code in the button, I do not want the contacts to know who is getting emailed so I am adding their emails to the Bcc field. In doing this Salesforce requires that you have a "to field". I am populating the additional to field with a donot reply email so that the system will take the code.
This will work for any object list view just change the object from contact to your desired object.

Behavior is Execute JavaScript
Display Type List button
{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/25.0/apex.js")} 

var emailAddresses = ''; 
var records = {!GETRECORDIDS($ObjectType.Contact)}; 
if (records[0] == null) {
    alert("Please select at least one record to update.");
} else {
for(var c = 0; c < records.length; c++) 

var contactRecord = sforce.connection.query("SELECT Email FROM Contact WHERE Id ='"+ records[c] 
+"'"); 

emailAddresses = emailAddresses + contactRecord.records.Email + ";"; 

}
location.replace('/email/author/emailauthor.jsp?retURL=/{!Contact.Id}&rtype=003&p24=someemail@somecompany.com&template_id=(your_template_ID)&p5='+emailAddresses);
Marcel HobizalMarcel Hobizal
@Devon, I've used your code above and it works great!  Is there any chance to do your loop above from a list view, but not send email, just to execute the below java for the contacts that you are checked in the list view?

This code below is javascript from DocuSign.

{!REQUIRESCRIPT("/apex/dsfs__DocuSign_JavaScript")}
//********* Option Declarations (Do not modify )*********//
var RC = ''; var RSL=''; var RSRO=''; var RROS=''; var CCRM='';
var CCTM=''; var CCNM=''; var CRCL=''; var CRL=''; var OCO='';
var DST=''; var LA=''; var CEM=''; var CES=''; var STB='';
var SSB=''; var SES=''; var SEM=''; var SRS=''; var SCS ='';
var RES=''; 
//*************************************************// 
CRL = 'Email~{!Contact.Email};LastName~{!JSENCODE(Contact.LastName)};Role~A;RoutingOrder~1';
CCRM = 'A~Signer 1';
CCTM = 'A~Signer';
CRCL = '';
OCO = 'Send'; 
DST = '123456'; 
LA = '0'; 
CEM = ''; 
CES = ''; 
RES = ''; 
CES = '{!JSENCODE(Contact.Name)} - HR Documentation Packet 2015';
CEM = '{!Contact.FirstName},\\n\\nPlease review, complete and sign the attached HR Documentation Packet 2015.\\n\\nKind Regards,\\n{!User.FirstName}\\n\\n{!User.FirstName} {!User.LastName}\\n{!User.Title}\\n\\nMain {!User.Main_Phone__c}\\nDirect {!User.Phone}\\nFax {!User.Fax}';
//********* Page Callout (Do not modify) *********// 
window.location.href = "/apex/dsfs__DocuSign_CreateEnvelope?DSEID=0&SourceID={!Contact.Id}&RC="+RC+"&RSL="+RSL+"&RSRO="+RSRO+"&RROS="+RROS+"&CCRM="+CCRM+"&CCTM="+CCTM+"&CRCL="+CRCL+"&CRL="+CRL+"&OCO="+OCO+"&DST="+DST+"&CCNM="+CCNM+"&LA="+LA+"&CEM="+CEM+"&CES="+CES+"&SRS="+SRS+"&STB="+STB+"&SSB="+SSB+"&SES="+SES+"&SEM="+SEM+"&SRS="+SRS+"&SCS="+SCS+"&RES="+RES;
//*******************************************/
Devon SacksDevon Sacks
You can and basically the part of my script that is processing that part I will put below with notes. 

//***** Gets the Records*****//
{!GETRECORDIDS($ObjectType.Contact)}; 
//***** Checks if there are Records selected from the list*****//
if (records[0] == null) {
    alert("Please select at least one record to update.");
} else {
//***** filters through the records*****///
for(var c = 0; c < records.length; c++) 

//***** This part is key the ~ sforce.connection~ can do anything you need from updating records and running queries. *****//
var contactRecord = sforce.connection.query("SELECT Email FROM Contact WHERE Id ='"+ records[c] 
+"'"); 

So using the above information if your looking for objects other than the email you would place those in the SOQL query. Or if you need you can replace the .query with .update and update records instead of running a query. I have done this and I have yet to using the update function find a way to know when the system is finished. I usually just attatch a debug or alert for errors at the end. The update takes a minute or two to process and posts a message if there are errors. I have yet to figure out how to create a progress bar.

Hope this helps
Vince NatteriVince Natteri
This is awesome. One question:
1) I have a Custom Object called Consideration. In that, I have two fields, Contact and Job. I want to mass mail a bunch of guys who are under this "Consideration" list. Is there anyway I can tweak this code or is this just for Contacts?

Thanks
Devon SacksDevon Sacks
Change the 
{!GETRECORDIDS($ObjectType.Contact)}

to 

{!GETRECORDIDS($ObjectType.Consideration__c)}

And change 
ar contactRecord = sforce.connection.query("SELECT Email FROM Contact WHERE Id ='"+ records[c] 
+"'");
to something like this

ar contactRecord = sforce.connection.query("SELECT Contact__c, Job__c FROM Consideration__c WHERE Id ='"+ records[c] 
+"'");

than you would need to add something like this to get the contact emails

contacts = contacts + contactRecord.records.Contact__c + ";"; 

and than add something like this
contactemails = sforce.connection.query("SELECT Email FROM Contact WHERE Id ='"+ contacts[c] 
+"'");

emailAddresses = emailAddresses + contactsemails.contacts.Email + ";"; 

}
location.replace('/email/author/emailauthor.jsp?retURL=/{!Contact.Id}&rtype=003&p24=someemail@somecompany.com&template_id=(your_template_ID)&p5='+emailAddresses);

not sure how well this will work given I am not sure if your Contact__c field is a relation field and contains the contact ID but I think you might be able to get it to work this way. A quicker way to make this work would be to map one of the fields in Consideration to capture the Contacts email and than you could skip most of the steps and directly pull the email from the Consideration object
 
Vicki KendallVicki Kendall

Hi Devon and Deepak

Are you able to help me?

I've used the code you provided initially (with the additional line 
{!REQUIRESCRIPT('/soap/ajax/28.0/connection.js')} at the start)

I am trying to send a mass email from a list view of a custom object (Subject_Request__c)
I have a contact field on the Subject Request object (or can change this to an email field if that is simpler)

I've changed 
{!GETRECORDIDS($ObjectType.Contact)}
to 
{!GETRECORDIDS($ObjectType.Subject_Request_cc )}

Is this correct? What else do I need to do? 

Apologies but I am new to this with barely a technical bone in my body so you may need to step me through it! The answer may even be in the above posts, but I haven't been able to work it out.

I'm getting the message Conrad was getting about my emails being available for processing, but nothing is sending.

Thanks,

Vicki 
Vince NatteriVince Natteri
Thank you Devon. I do have on question. When I select ONE item from my Consideration object, it works fine. For more than one selection, it does not work. I am not sure why. Here's my code:

function sendMail(){
    var contactIds='';
    var templateId = jQuery('[id=email-template]').val();
    var emailAddresses = ''; 
    var records = {!GETRECORDIDS($ObjectType.Consideration_List__c)};     
    
    if (records[0] == null) {
    alert("Please select at least one record to update.");
        } else {
        //***** filters through the records*****///
        for(var c = 0; c < records.length; c++) 
        { 
        //***** This part is key the ~ sforce.connection~ can do anything you need from updating records and running queries. *****//
        var contactRecord = sforce.connection.query("SELECT Candidate_Name__c FROM Consideration_List__c WHERE Id ='"+ records[c] +"'"); 

        var interimString=contactRecord.records.Candidate_Name__c;
        interimString=interimString.substring(0,interimString.length-3);
        contactIds = contactIds + interimString + ","; 
            } 
        }
        
        contactIds=removeLastComma(contactIds);
    
    if(contactIds.length>0 && templateId!=''){
        var massMailRequest = new sforce.MassEmailMessage();
        massMailRequest.targetObjectIds = contactIds;
        massMailRequest.templateId = templateId;
        massMailRequest.replyTo = 'noreply@salesforce.com';

        sforce.connection.sendEmail([massMailRequest]);

        alert('Your emails ' + contactIds + ' have been submitted for processing.');
    }
}
Vince NatteriVince Natteri
Just to add, I remvoed the last 3 characters because it works only for 15 digit Ids. But, I'm still not sure why it doesn't work for more than 1 selection. I can see all the selections separated by a comma from the Alert Box at the end. Just not sure what is wrong. Thank you!
Vince NatteriVince Natteri
Apologies everyone. Got it to work. Just used 'push' and removed all the substring and it worked fine! Quick question:

Instead o:
 
massMailRequest.replyTo = 'noreply@salesforce.com';

how do I Reply To the user who us currently logged in and sends that mass mail? i.e. the current user's email?

Thanks!
 
Anish DamodaranAnish Damodaran
Vince,
I am trying to use this code for one of my custom object. You have mentioned that its worked fine with push statement instead of substring. Is it something like this. Could you please help me..

function sendMail(){
    var contactIds='';
    var templateId = jQuery('[id=email-template]').val();
    var emailAddresses = '';
    var records = {!GETRECORDIDS($ObjectType.Rep_Group__c)};    
   
    if (records[0] == null) {
    alert("Please select at least one record to update.");
        } else {
        //***** filters through the records*****///
        for(var c = 0; c < records.length; c++)
        {
        //***** This part is key the ~ sforce.connection~ can do anything you need from updating records and running queries. *****//
        var contactRecord = sforce.connection.query("SELECT Email__c FROM Rep_Group__c WHERE Id ='"+ records[c] +"'");

        var interimString=contactRecord.records.Email__c;
               contactIds.push(interimString);

            }
        }
       
        //contactIds=removeLastComma(contactIds);  is this still required??

if(contactIds.length>0 && templateId!=''){
        var massMailRequest = new sforce.MassEmailMessage();
        massMailRequest.targetObjectIds = contactIds;
        massMailRequest.templateId = templateId;
        massMailRequest.replyTo = 'noreply@salesforce.com';

        sforce.connection.sendEmail([massMailRequest]);

        alert('Your emails ' + contactIds + ' have been submitted for processing.');
    }
}
 
Vince NatteriVince Natteri
Hi Anish,

I am not a JS guy. Just played around with it until it works. Here's the code that works fine for me. You obviously need to change the custom object references. Good luck!

function sendMail(){
    var contactIds=[];
    var templateId = jQuery('[id=email-template]').val();
    var emailAddresses = ''; 
    var records = {!GETRECORDIDS($ObjectType.Consideration_List__c)};     
    
    if (records[0] == null) {
    alert("Please select at least one record to update.");
        } else {
        //***** filters through the records*****///
        for(var c = 0; c < records.length; c++) 
        { 
        //***** This part is key the ~ sforce.connection~ can do anything you need from updating records and running queries. *****//
        var contactRecord = sforce.connection.query("SELECT Candidate_Name__c FROM Consideration_List__c WHERE Id ='"+ records[c] +"'"); 

        var interimString=contactRecord.records.Candidate_Name__c;
        //interimString=interimString.substring(0,interimString.length-3);
        contactIds.push(interimString);
        
            } 
        }
        
        
    
    if(contactIds.length>0 && templateId!=''){
        var massMailRequest = new sforce.MassEmailMessage();
        massMailRequest.targetObjectIds = contactIds;
        massMailRequest.templateId = templateId;
        //massMailRequest.replyTo = 'noreply@salesforce.com';

        sforce.connection.sendEmail([massMailRequest]);

        alert('Your emails ' + contactIds + ' have been submitted for processing.');
    }
}
Ricardo DiazRicardo Diaz
@Deepak and @Vince thanks for the code snippet!

Currently trying to adapt it to Cases. For example, I would like for the button to send an email to the checked Case's Contact. I replaced the values as instructed and changed the query to look at the ContactId field from Case. 

Unfortunately, I am not receiving any output. Nothing in my Mass Email queue and no email on the receptor's end. 

Thoughts? Much appreciated!

User-added image

Code block modifications:
 
function sendMail(){
    var contactIds=[];
    var templateId = jQuery('[id=email-template]').val();
    var emailAddresses = ''; 
    var records = {!GETRECORDIDS($ObjectType.Case)};     
    
    if (records[0] == null) {
    alert("Please select at least one record to update.");
        } else {
        //***** filters through the records*****///
        for(var c = 0; c < records.length; c++) 
        { 
        var contactRecord = sforce.connection.query("SELECT ContactId FROM Case WHERE Id ='"+ records[c] +"'"); 
        var interimString=contactRecord.records.Contact;
        contactIds.push(interimString);
            } 
        }
            
    if(contactIds.length>0 && templateId!=''){
        var massMailRequest = new sforce.MassEmailMessage();
        massMailRequest.targetObjectIds = contactIds;
        massMailRequest.templateId = templateId;
        sforce.connection.sendEmail([massMailRequest]);

        alert('Your emails ' + contactIds + ' have been submitted for processing.');
    }
}

Whole block:
 
{!REQUIRESCRIPT('/soap/ajax/28.0/connection.js')}
{!REQUIRESCRIPT('/soap/ajax/29.0/connection.js')}
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')}
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js')}

function appendTags(){
    if(jQuery('[id=start-theme-css]').length==0){
        jQuery('head').append(
            '<link ' + 
                'id="start-theme-css"' + 
                'rel="stylesheet"' + 
                'href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.min.css"' + 
                'type="text/css" />'
        );

        jQuery('body').append(
            '<div id="dialog-confirm" title="Send Email">' + 
                '<p style="text-align:justify">' + 
                    '<img src="/s.gif" alt="Case" class="pageTitleIcon" title="Case" style="margin: 0 7px 30px 0"/>' + 
                    'Please select an email template to use. To create a new template, you must exit this mass email process and create the new template in your personal setup section.' + 
                    '<br/><br/>Email Template:<br/>' + 
                    '<select id="email-template" style="width:380px"></select>' +
                '</p>' + 
            '</div>'
        ); 
    }
}

function createPopupWindow(){
    jQuery(function() {
        jQuery( "#dialog-confirm" ).dialog({
            resizable: false,
            width: 400,
            modal: true,   
            buttons: {
                "Send Mail": 
                    function() {
                        sendMail();
                    },
                
                Cancel: 
                    function() {
                        jQuery( this ).dialog( "close" );
                    }
            }
        });
    });
}

function fetchEmailTemplates(){
    var emailTemplates = 
        sforce.connection.query(
            'SELECT Id, Name FROM EmailTemplate WHERE IsActive = TRUE ORDER BY Name',
            {
                onSuccess: 
                    function(result){
                        var records = result.getArray('records');
                        var innerHtml = '<option value="">--Select--</option>';
                        for(var i=0; i<records.length; i++)
                            innerHtml += 
                                '<option value="' + records[i].Id + '">' + 
                                    records[i].Name +
                                '</option>';

                        jQuery('[id=email-template]').html(innerHtml);
                    },
                onFailure:
                    function(error){
                        alert('An Error has Occurred. Error: ' + error);
                    }
            }
        );
}
function sendMail(){
    var contactIds=[];
    var templateId = jQuery('[id=email-template]').val();
    var emailAddresses = ''; 
    var records = {!GETRECORDIDS($ObjectType.Case)};     
    
    if (records[0] == null) {
    alert("Please select at least one record to update.");
        } else {
        //***** filters through the records*****///
        for(var c = 0; c < records.length; c++) 
        { 
        var contactRecord = sforce.connection.query("SELECT ContactId FROM Case WHERE Id ='"+ records[c] +"'"); 
        var interimString=contactRecord.records.Contact;
        contactIds.push(interimString);
            } 
        }
            
    if(contactIds.length>0 && templateId!=''){
        var massMailRequest = new sforce.MassEmailMessage();
        massMailRequest.targetObjectIds = contactIds;
        massMailRequest.templateId = templateId;
        sforce.connection.sendEmail([massMailRequest]);

        alert('Your emails ' + contactIds + ' have been submitted for processing.');
    }
}

appendTags();
fetchEmailTemplates();
createPopupWindow();

 
Ricardo DiazRicardo Diaz
OK, figured it out!

Just had missed one value assignment. Thanks again for this code!
var contactRecord = sforce.connection.query("SELECT ContactId FROM Case WHERE Id ='"+ records[c] +"'"); 
        var interimString=contactRecord.records.ContactId;
Tim PageTim Page
Hi Deepak and Vince,

I'm trying to use Deepak's script from Github on a custom Object called BEC Home (BEC_Home__c). The Object has a contact (Contact__c) and Contact Email (Contact_Email__c) fields included. I tried a bunch of variations of the code below, but never got it to send. The pop up seemed to work, it just never actually sent the mass email.

Thanks,
Tim


+{!REQUIRESCRIPT('/soap/ajax/29.0/connection.js')}
+{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')}
+{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js')}
+
+function appendTags(){
+ if(jQuery('[id=start-theme-css]').length==0){
+ jQuery('head').append(
+ '<link ' +
+ 'id="start-theme-css"' +
+ 'rel="stylesheet"' +
+ 'href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.min.css"' +
+ 'type="text/css" />'
+ );
+
+ jQuery('body').append(
+ '<div id="dialog-confirm" title="Quick Mass Mailer">' +
+ '<p style="text-align:justify">' +
+ '<img src="/s.gif" alt="Contact" class="pageTitleIcon" title="Contact" style="margin: 0 7px 30px 0"/>' +
+ 'Please select an email template to use. To create a new template, you must exit this mass email process and create the new template in your personal setup section.' +
+ '<br/><br/>Email Template:<br/>' +
+ '<select id="email-template" style="width:380px"></select>' +
+ '</p>' +
+ '</div>'
+ );
+ }
+}
+
+function createPopupWindow(){
+ jQuery(function() {
+ jQuery( "#dialog-confirm" ).dialog({
+ resizable: false,
+ width: 400,
+ modal: true,
+ show: {
+ effect: "bounce",
+ duration: 500
+ },
+ hide: {
+ effect: "bounce",
+ duration: 500
+ },
+ buttons: {
+ "Send Mail":
+ function() {
+ sendMail();
+ },
+
+ Cancel:
+ function() {
+ jQuery( this ).dialog( "close" );
+ }
+ }
+ });
+ });
+}
+
+function fetchEmailTemplates(){
+ var emailTemplates =
+ sforce.connection.query(
+ 'SELECT Id, Name FROM EmailTemplate WHERE IsActive = TRUE ORDER BY Name',
+ {
+ onSuccess:
+ function(result){
+ var records = result.getArray('records');
+ var innerHtml = '<option value="">--Select--</option>';
+ for(var i=0; i<records.length; i++)
+ innerHtml +=
+ '<option value="' + records[i].Id + '">' +
+ records[i].Name +
+ '</option>';
+
+ jQuery('[id=email-template]').html(innerHtml);
+ },
+ onFailure:
+ function(error){
+ alert('An Error has Occurred. Error: ' + error);
+ }
+ }
+ );
+}
+
+function sendMail(){
+ var contactIds = {!GETRECORDIDS( $ObjectType.Contact )};
+ var templateId = jQuery('[id=email-template]').val();
+ if(contactIds.length>0 && templateId!=''){
+ var massMailRequest = new sforce.MassEmailMessage();
+ massMailRequest.targetObjectIds = contactIds;
+ massMailRequest.templateId = templateId;
+ massMailRequest.replyTo = 'noreply@salesforce.com';
+
+ sforce.connection.sendEmail([massMailRequest]);
+
+ alert('Your emails have been submitted for processing.');
+ }
+}
+
+appendTags();
+fetchEmailTemplates();
+createPopupWindow();
Ashik ShettyAshik Shetty
Hi, @Deepak Can you tell me how should I use this code? . I have created a list view button under Contact and tried, but it is not showing.
Tim PageTim Page
Hi Pierre, I believe I just saw this in the Winter release of Lightening. You might look into it. Tim