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
SMasterSMaster 

Send Email to the Selected Records from the Default View Page.

Hi All,

 

I require an urgent help.

 

The requirement is that i need to provide a custom button on the Default List View Page to send an Email to the selected record's Email Id field.

 

The records will be selected using the Action Checkbox provided i.e. i need to check the CheckBox provided under Action column to select the records, and after selecting the records click on the Custom button to send the Email to all.

 

Can it be done, if yes please let me know How....Its urgent Please..

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Imran MohammedImran Mohammed

I made a mistake and apologies for that.

Just change the code from the for loop

 

for (var i=0; i< records.length; i++) {

var record = records[i];

emailAddresses += record.Email_Address__c;

if((i+1) != records.length)
{
emailAddresses += ',';
}
}

emailAddresses += '';

req.toAddresses = emailAddresses.toString().split(',');
var sendEMail = sforce.connection.sendEmail([req]);

 

Let me know if it works.

All Answers

Imran MohammedImran Mohammed

Yes, this can be done.

I have few questions, Does the current object has a lookup field to the User? I mean to say is there any custom field that is of lookup type to User.

SMasterSMaster

Hello Sir,

 

Actually No, i do not have any lookup field in this object. However i have an email field to which i need to send an email. Thanks.

Imran MohammedImran Mohammed

Yes can be done.

 

//in your custom button javascript add the below code.

{!requireScript("/soap/ajax/20.0/connection.js")} 

{!requireScript("/soap/ajax/20.0/apex.js")} 

//Make the changes accordingly to the below code.

var recordsSelected = {!GETRECORDIDS( $ObjectType.<<Current Custom Object >>)}; 

// Now you have the ids of the selected records.

//Query the same object to get Email field vals.

//Then use the below code and populate the toAddresses field

var req = new sforce.SingleEmailMessage();

 req.replyTo = "<<any email id>>";

 req.subject = "<<Custom Message>>";

 req.plainTextBody = "<<Custom Message>>";

//populate the toAddresses field iterating through the list you queried above

req.toAddresses = [<<Email Ids>>];

var sendEMail = sforce.connection.sendEmail([req]);

SMasterSMaster

Thanks Sir,

 

Do i need to create an Apex class for this..And do i need to create the visualforce page also??

 

And Sir.. i have created a custom List button on the Default view page.. how will i be able to call this there?? or is there any other approach i have to follow.. please guide..

 

Imran MohammedImran Mohammed

It depends on your choice of solution.

You can either go with Apex and VF or do it using ajax.

 

For the code which i sent does not require to create VF and Apex controller. Try that if you want.

If time permits i will tell you how to create VF and Apex and achieve the functionality you want.

SMasterSMaster

Sir,

 

I simply have no idea how to implement the code provided by you.. that's why i was asking such questions. Anyhow..i want to go with the soluton provided by you.. just need some more help from your side in implementing this.

 

please let me know where do i have to write this...

 

Inside the Custom List Button, where content source is Onclick Javascript?? or anywhere else...

 

From my questions you can understand that i have just started working on this.. so please continue your help & support

super developersuper developer

You need to Write in

Execute JavaScript in list button.

 

Try

SMasterSMaster

Hello Sir,

 

I have tried it exactly on the same place but while running it always gives an error, Expected ";" I am not able to understand why so. Please help me on this

SMasterSMaster

Hello Sir,

 

I have tried it on custom button javascript but while running it always gives an error, Expected ";" I am not able to understand why so. Please help me on this

super developersuper developer

Did you Replaced the What you need in above suggested code

 

Imran MohammedImran Mohammed

Post the code as it is you have added in Custom button javascript.

I will try to find the issue.

SMasterSMaster

Hello Sir,

 

I have used the following code that i have used in Custom button javascript with the following details:

 

Display Type:  List Button

Behavior: Execute Javascript

Content Source: OnClick Javascript

Display Checkbox is checked for multiselection

 

 

My Custom Object Name is RMG_Employee_Master__c & inside that custom object my custom email field is Email_Address__c.

 

 

//in your custom button javascript add the below code.
{!requireScript("/soap/ajax/20.0/connection.js")}
{!requireScript("/soap/ajax/20.0/apex.js")}
//Make the changes accordingly to the below code.
var recordsSelected = {!GETRECORDIDS( $ObjectType.RMG_Employee_Master__c)};
// Now you have the ids of the selected records.
//Query the same object to get Email field vals.
public List<RMG_Employee_Master__c> email;
email = [select Email_Address__c from RMG_Employee_Master__c  where Email_Address__c = :ApexPages.currentPage().getParameters().get('Email_Address__c')?];
//Then use the below code and populate the toAddresses field
var req = new sforce.SingleEmailMessage();
 req.replyTo = "SMaster@gmail.com";
 req.subject = "hello";
 req.plainTextBody = "hello";
//populate the toAddresses field iterating through the list you queried above
req.toAddresses = [email];
var sendEMail = sforce.connection.sendEmail([req]);


 

SMasterSMaster

Sir,

 

I have posted the code  which i have used please have a look at & kindly let me know my mistake.

Imran MohammedImran Mohammed

Hi,

 

Try the below code.

 

//in your custom button javascript add the below code.
{!requireScript("/soap/ajax/20.0/connection.js")}
{!requireScript("/soap/ajax/20.0/apex.js")}

var recordsSelected = {!GETRECORDIDS( $ObjectType.RMG_Employee_Master__c)};

if(recordsSelected.length > 0)

{

var emIdList = "('" + recordsSelected.join("','") + "')";

 

var result = sforce.connection.query('select Email_Address__c from RMG_Employee_Master__c  where id in '+emIdList);

var records = result.getArray("records");

 

//Then use the below code and populate the toAddresses field

var req = new sforce.SingleEmailMessage();

 req.replyTo = "SMaster@gmail.com";

 req.subject = "hello";

 req.plainTextBody = "hello";

 

 var emailAddresses = '';

 for (var i=0; i< records.length; i++) {

var record = records[i];

emailAddresses += '"+record.Email_Address__c+"';

if((i+1) != records.length)

{

emailAddresses += ',';

}

}

 

//populate the toAddresses field iterating through the list you queried above

req.toAddresses = [emailAddresses];

var sendEMail = sforce.connection.sendEmail([req]);

}

 

 

Let me know if you face any issues.

SMasterSMaster

Hello Sir,

 

I do not encounter any exception or error this time. But after selecting one or two records if i click on the button no email is getting fired. Please let me know have i missed something....

Imran MohammedImran Mohammed

I feel that should work.

Can you add an alert and see if the emailAddresses variable holds the email addresses or not?

alert(emailAddresses);

Let me know after you do it.

SMasterSMaster

Sir,

 

I have used this and on clicking the button it gives "+record.Email_Address__c+"

 

It seems that emailAddresses variable does not holds the email addresses......

 

Imran MohammedImran Mohammed

Post the entire javascript code. i would like to see that.

SMasterSMaster

Sir,

 

 

//in your custom button javascript add the below code..
{!requireScript("/soap/ajax/20.0/connection.js")}
{!requireScript("/soap/ajax/20.0/apex.js")}
var recordsSelected = {!GETRECORDIDS( $ObjectType.RMG_Employee_Master__c)};

if(recordsSelected.length > 0)

{

var emIdList = "('" + recordsSelected.join("','") + "')";



var result = sforce.connection.query('select Email_Address__c from RMG_Employee_Master__c where id in '+emIdList);

var records = result.getArray("records");



//Then use the below code and populate the toAddresses field

var req = new sforce.SingleEmailMessage();

req.replyTo = "SMaster@gmail.com";

req.subject = "hello";

req.plainTextBody = "hello";



var emailAddresses = '';

for (var i=0; i< records.length; i++) {

var record = records[i];

emailAddresses += '"+record.Email_Address__c+"';

if((i+1) != records.length)

{

emailAddresses += ',';

}

}

alert(emailAddresses);



//populate the toAddresses field iterating through the list you queried above

req.toAddresses = [emailAddresses];
var sendEMail = sforce.connection.sendEmail([req]);

}

Imran MohammedImran Mohammed

Change this line  from emailAddresses += '"+record.Email_Address__c+"';  

to emailAddresses += '"'+record.Email_Address__c+'"';

Let me know if this works.

SMasterSMaster

Sir,

 

Now..alert is showing the exact mail id of the record selected. But emails are not firing...

 

To do this i remove alert..select one record..and click the button..no email has been sent out...

Imran MohammedImran Mohammed

Can you send what is it showing in the alert for emailAddresses?

Try this with atleast two records selected.

SMasterSMaster

Sir,

 

If i select two records and click the button alert shows like this

 

"ackyshah@gmail.com","smalik@gmail.com"

 

 

bothe the correct mail id seperated with comma..

Imran MohammedImran Mohammed

Then this should work fine. Please check the email accounts once again.

Let me know if it doesn't work.

SMasterSMaster

Sir,

 

I have tested with multiple email accounts..but i do not know why is it not working for me..

 

does it take more time to fire the mail.... or anything else i am missing... i am totally blank....

SMasterSMaster

Sir,

 

I have tested with multiple email accounts..even with email accounts of other domain , but i do not know why is it not working for me..

 

does it take more time to fire the mail.... or anything else i am missing... i am totally blank....

Imran MohammedImran Mohammed

To confirm, are they valid email address?

Imran MohammedImran Mohammed

Comment the below line in the code

//req.toAddresses = [emailAddresses];

and add this line and see 

req.toAddresses = ["abc@gmail.com","Your email address"];

Can you do that?

 

Imran MohammedImran Mohammed

Hey, i got two emails from you. This means its working fine.

Check whether the mail ids you used earlier are valid or not.

SMasterSMaster

Sir,

 

Please confirm with which email ids you have received the test mails..

Imran MohammedImran Mohammed

I got the email from ashish.garg@headstrong.com .

In the to address of email, my email id was there and ashish.garg@headstrong.com email id was there.

 

Now you uncomment the below line which i said earlier and test.

req.setAddresses = [emailAddresses];

 

It should work and make sure that the email ids in your custom object records are valid.

 

Imran MohammedImran Mohammed

Can you share your email id so that i can forward the email i got?

SMasterSMaster

its the same ashish.garg@headstrong.com

 

Sir.. since you have received the Mails from this email id, it means this mail id is correct.. and i have used the same mail id in the email fields of record i have created. But still no mail is coming to this mail id.. why is this happening...

Imran MohammedImran Mohammed

I am not sure on this. But i will recommend you to recheck the email id entered in the record.

Or do one thing, enter my email id in the record instead of yours and then select the record and click the custom button.

I will see if i receive any email.

SMasterSMaster

Sir,

 

I have clicked the button.. please forward me the mail.. once received...

SMasterSMaster
Sir, Did you receive any mail...
Imran MohammedImran Mohammed

i did not get any email.

Let me check once.

Imran MohammedImran Mohammed

I made a mistake and apologies for that.

Just change the code from the for loop

 

for (var i=0; i< records.length; i++) {

var record = records[i];

emailAddresses += record.Email_Address__c;

if((i+1) != records.length)
{
emailAddresses += ',';
}
}

emailAddresses += '';

req.toAddresses = emailAddresses.toString().split(',');
var sendEMail = sforce.connection.sendEmail([req]);

 

Let me know if it works.

This was selected as the best answer
Imran MohammedImran Mohammed

Did it work for you?

SMasterSMaster

Yes Sir.....

 

Many Many Thanks to you sir....to make this happen......Its working perfectly....  :smileyhappy:

 

Sir.. i have few more things to do in this....please allow me to to ask those as well...

 

I am marking this as Accepted Solution.....

 

 

 

 

 

 

SMasterSMaster

I shall never forget your effort & time in resolving this....

 

Imran MohammedImran Mohammed

I will recommend you to get start learning Apex and Visualforce.

Please find the links below

Visualforce

Apex

super developersuper developer

Hi both of you,

 

I Followed you both i tried this on account with email__c. I am not getting any mail  My code is below.

See and tell me where i did mistake

 

{!requireScript("/soap/ajax/20.0/connection.js")}
{!requireScript("/soap/ajax/20.0/apex.js")}
var recordsSelected = {!GETRECORDIDS( $ObjectType.Account)};
if(recordsSelected.length > 0)
{
var emIdList = "('" + recordsSelected.join("','") + "')";
var result = sforce.connection.query('select Email__c from Account where id in '+emIdList);
var records = result.getArray("records");
alert(records.length);
//Then use the below code and populate the toAddresses field
var req = new sforce.SingleEmailMessage();
req.replyTo = "radhika_y@dskvap.com";
req.subject = "hello";
req.plainTextBody = "hello";
var emailAddresses = '';
for (var i=0; i< records.length; i++) {
var record = records[i];
if(record.Email__c!=null){
emailAddresses += record.Email__c;

if((i+1) != records.length)
{
emailAddresses += ',';
}
}
}
emailAddresses += '';
alert(emailAddresses.toString().split(','));
req.toAddresses = emailAddresses.toString().split(',');
var sendEMail = sforce.connection.sendEmail([req]);
}

 

Thanks in advance

 

Imran MohammedImran Mohammed

Are the alerts showing the correct data which you have put in the code?

super developersuper developer

Hi Imran,

 

The emailaddresses alert not showing any thing. the above one showing correctly.

 

Thanks

------------

Radhika.Y

Imran MohammedImran Mohammed

Add an alert in the for loop and see if emailAddresses are concatenated?

super developersuper developer

I tried like that also but i didn't get any thing there

 

Thanks

-----------

Radhika.Y

Imran MohammedImran Mohammed

I mean to say, try to alert record.Email__c as well as emailAddress inside the for loop.

super developersuper developer

ya

 

i tried same but i didn't get any thing.

 

Thanks

Imran MohammedImran Mohammed

Is it atleast entering the for loop and showing an alert?

super developersuper developer

{!requireScript("/soap/ajax/20.0/connection.js")}
{!requireScript("/soap/ajax/20.0/apex.js")}
var recordsSelected = {!GETRECORDIDS( $ObjectType.Account)};
if(recordsSelected.length > 0)
{
var emIdList = "('" + recordsSelected.join("','") + "')";
var result = sforce.connection.query('select id,Email__c from Account where id in '+emIdList);
var records = result.getArray("records");
alert(records);
//Then use the below code and populate the toAddresses field
var req = new sforce.SingleEmailMessage();
req.replyTo = "radhika_y@dskvap.com";
req.subject = "hello";
req.plainTextBody = "hello";
var emailAddresses = '';
for (var i=0; i< records.length; i++) {
var record = records[i];
alert(record.id);// i'm getting undefined
alert(record.email__c);//here printing value
emailAddresses += record.Email__c;
alert( emailAddresses+""+i);//i'm getting undefined with loop value 1,2,3...
alert( emailAddresses+""+i);i'm getting undefined with loop value 1,2,3....

if((i+1) != records.length)
{
emailAddresses += ',';
}
}
emailAddresses += '';
req.toAddresses = emailAddresses.toString().split(',');
var sendEMail = sforce.connection.sendEmail([req]);
}

nikkitorschnikkitorsch
I have a similar request/question. Can someone help me out? I'm trying to create two custom buttoms to select multiple records and submit them for approval or approve. Your help is greatly appreciated.
sriharisfdc reddysriharisfdc reddy
hi Imran,

   this is good..but in the same i want to send the email template
    
    so i am wrote the 
       req.templateId="Number";
  but the emails are not going may i knw the reason
   if i write plaintexxt then its working

thanking u

 
Ben HeissBen Heiss
I have attempted to follow this solution and having a little trouble implementing it to what I want. I have contact roles that are connect to a record. I want to return and send emails to all contact roles emails that are associated to that record. My code is currently:

//in your custom button javascript add the below code.
{!requireScript("/soap/ajax/20.0/connection.js")}
{!requireScript("/soap/ajax/20.0/apex.js")}
var claim = Name__c;
var recordsSelected = {!GETRECORDIDS( $ObjectType.Contact_Roles__c)};
if(recordsSelected.length > 0)
{
//var emIdList = "('" + recordsSelected.join("','") + "')";
 
var result = sforce.connection.query('select Email__c from Contact_Roles__c  where Claim__c = claim);
var records = result.getArray("records");
alert(records.length);
//Then use the below code and populate the toAddresses field
var req = new sforce.SingleEmailMessage();
req.replyTo = "heissbeast@gmail.com";
req.subject = "hello";
req.plainTextBody = "hello";
 
var emailAddresses = '';
for (var i=0; i< records.length; i++) {
var record = records[i];
emailAddresses += '"'+record.Email__c+'"';
if((i+1) != records.length)
{
emailAddresses += ',';
}
}

alert(emailAddress);
 
//populate the toAddresses field iterating through the list you queried above
req.toAddresses = [emailAddresses];
var sendEMail = sforce.connection.sendEmail([req]);
}

I'm getting an "invalid or unexpected token" error.
Thank you for your help.
Thulasi ReddysThulasi Reddys
I need a code for Send Email to the Selected Records using Lightning Component?
rishabh rathor 18rishabh rathor 18
Hi 
Imran Mohammed
Here Its my Component and i m facing issue with send email to selected record.
=============== Component===========
<aura:component controller="Selected_Contact_Email" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="selectedContact" type="list"/>
    <aura:attribute name="contactList" type="list"/>
    <aura:attribute name="listOfAllContact" type="list"/>
    <aura:attribute name="selectedCount" type="integer" default="0"/>
     <div  aura:id="Selected_Contact_Email" class="slds"> 
          <table class="slds-table slds-table_bordered slds-table_cell-buffer">
                <thead>
                    <tr class="slds-text-title_caps">
                    <!--header checkbox for select all-->
                        <th style="width:3.25rem;" class="slds-text-align_right">
                            <div class="slds-form-element">
                                <div class="slds-form-element__control">
                                    <label class="slds-checkbox">
                                        <ui:inputCheckbox disabled="{!v.totalRecordsCount == 0}"
                                                          aura:id="selectAllId"
                                                          change="{!c.selectAllCheckbox}"/>
                                        <span class="slds-checkbox_faux"></span>
                                        <span class="slds-form-element__label"></span>
                                    </label>
                                </div>
                            </div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Name">Name</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Phone">Phone</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Type">Email</div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <aura:iteration items="{!v.contactList}" var="obj">
                        <tr>
                            <th scope="row" class="slds-text-align_right" style="width:3.25rem;">
                                <div class="slds-form-element">
                                    <div class="slds-form-element__control">
                                        <label class="slds-checkbox">
                                            <ui:inputCheckbox text="{!obj.objConatct.Id}"
                                                              value="{!obj.isChecked}"
                                                              change="{!c.checkboxSelect}"/>
                                            <span class="slds-checkbox_faux"></span>
                                            <span class="slds-form-element__label text"></span>
                                        </label>
                                    </div>
                                </div>
                            </th>
                            <th scope="row">
                                <div class="slds-truncate" title="{!obj.objAccount.Name}">
                                    {!obj.objConatct.Name}
                                </div>
                            </th> 
                            <th scope="row">
                                <div class="slds-truncate" title="{!obj.objConatct.Phone}">
                                    <lightning:formattedPhone value="{!obj.objConatct.Phone}"/>
                                </div>
                            </th>
                            <th scope="row">
                                <div class="slds-truncate" title="{!obj.objConatct.Email}">
                                     <lightning:formattedEmail value="{!obj.objConatct.Email}"/>
                                 <!--   {!obj.objConatct.Email}-->
                                </div>
                            </th>
                        </tr>
                    </aura:iteration>
                </tbody>
            </table>
         <lightning:button variant="brand" 
                                      aura:id="contactFieldbtn" 
                                      label="Send email" 
                                      onclick="{!c.send_Email}" /> 
    </div>
</aura:component>


================js Helper==============================
({
    doInitHelper : function(component, event, helper) {
        var action = component.get("c.fetchContactWrapper");
        console.log(action);
        var accountId = component.get("v.recordId");
        console.log(accountId) ;   
        action.setParams({
            accountIds: accountId
        });
        
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS') {
                var contactList = response.getReturnValue();
                component.set("v.contactList",contactList);
                console.log(contactList);
            }
            else {
                alert('Error in getting data');
            }
        });
        $A.enqueueAction(action);
    },
})
=================== Js Controller====================
({
    doInit : function(component, event, helper) {
        
        helper.doInitHelper(component, event, helper);
    },
    
     selectAllCheckbox: function(component, event, helper) {
        var selectedHeaderCheck = event.getSource().get("v.value");
        var updatedAllRecords = [];
        var updatedPaginationList = [];
        var listOfAllAccounts = component.get("v.listOfAllContact");
        var PaginationList = component.get("v.contactList");
        // play a for loop on all records list 
        for (var i = 0; i < listOfAllAccounts.length; i++) {
            // check if header checkbox is 'true' then update all checkbox with true and update selected records count
            // else update all records with false and set selectedCount with 0  
            if (selectedHeaderCheck == true) {
                listOfAllAccounts[i].isChecked = true;
                component.set("v.selectedCount", listOfAllAccounts.length);
            } else {
                listOfAllAccounts[i].isChecked = false;
                component.set("v.selectedCount", 0);
            }
            updatedAllRecords.push(listOfAllAccounts[i]);
        }
        // update the checkbox for 'PaginationList' based on header checbox 
        for (var i = 0; i < PaginationList.length; i++) {
            if (selectedHeaderCheck == true) {
                PaginationList[i].isChecked = true;
            } else {
                PaginationList[i].isChecked = false;
            }
            updatedPaginationList.push(PaginationList[i]);
        }
        component.set("v.listOfAllContact", updatedAllRecords);
        component.set("v.contactList", updatedPaginationList);
    },
 
    checkboxSelect: function(component, event, helper) {
        // on each checkbox selection update the selected record count 
        var selectedRec = event.getSource().get("v.value");
        var getSelectedNumber = component.get("v.selectedCount");
        if (selectedRec == true) {
            getSelectedNumber++;
        } else {
            getSelectedNumber--;
            component.find("selectAllId").set("v.value", false);
        }
        component.set("v.selectedCount", getSelectedNumber);
        // if all checkboxes are checked then set header checkbox with true   
        if (getSelectedNumber == component.get("v.totalRecordsCount")) {
            component.find("selectAllId").set("v.value", true);
        }
    },
    send_Email : function(component, event, helper) {
        
        console.log(' Email Sent');
    }
    
})
================== Apex controller==============
public class Selected_Contact_Email {
      @AuraEnabled 
    Public static Id AccountId{get;set;}
     @AuraEnabled 
    public static List<contactListWrapper> fetchContactWrapper(List<Id> accountIds){     
        List<contactListWrapper> lstaccountListWrapper = new List<contactListWrapper>();
        // query account records and create 'accountListWrapper' class instance for each record. 
        for(contact con : [SELECT Id, firstname,lastname,name, Email, Phone, AccountId FROM Contact WHERE accountId in : accountIds order by CreatedDate desc  Limit 10])
                          {
                               lstaccountListWrapper.add(new contactListWrapper(false,con));
                           } 
        return lstaccountListWrapper; 
    }
    
    /* wrapper class */  
    public class contactListWrapper {
        @AuraEnabled public boolean isChecked {get;set;}
        @AuraEnabled public  contact objConatct{get;set;}
        public contactListWrapper(boolean isChecked, contact objConatct){
            this.isChecked = isChecked;
            this.objConatct = objConatct;
        }
    }
  
    public Static void send_Email(){
        system.debug(' Email Sent');
    }

}


Plz Help asap.
Thanks In advance,
Rishabh Rathor