Friday, 3 January 2014

Sending emails to the selected roles email id if there are checkbox selected.

Problem:- Recently one of my friend asked me to post a code for the below requirement:-

If there are checkbox selected on a VF Page then he wanted to send an email to the CEO role and Admin role users.

Please let me know if any issue.
Solution: I gave a try and created a VF page with Standard controller and extension.
//VF Page

<apex:page standardController="Candidate__c" extensions="sendEmail">
 <apex:form >
  <apex:pageBlock >
   <apex:pageBlockButtons >
    <apex:commandButton value="SendEmail" action="{!sendEmailAlert}"/>
   </apex:pageBlockButtons>
  
   <apex:pageBlockSection >
  <apex:inputField value="{!Candidate__c.US_Citizen__c}"/>
    <apex:inputField value="{!Candidate__c.Visa_Required__c}"/>
 </apex:pageBlockSection>
 </apex:pageBlock>
 
 </apex:form>
</apex:page>

//COntroller

public class sendEmail
{
public Candidate__c candidate;

    public sendEmail(ApexPages.StandardController controller)
   {
     this.candidate = (Candidate__C)controller.getRecord();
     candidate.Visa_Required__c = false;
     candidate.US_Citizen__c = false;
    
        }

public Id userId;
List<User> emailAddr;

public void sendEmail()
{

if(candidate.US_Citizen__c == true && candidate.Visa_Required__c == true)
 {
sendEmailAlert();
 }
 }

public PageReference sendEmailAlert()
{
 String addresses;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

       emailAddr =  [select Email from User u where userRole.name in('Admin','SCEO')];
       addresses = emailAddr.get(0).Email;
     for(Integer i=1;i<emailAddr.size();i++)
      {
          System.Debug('Emai numbers' +emailAddr.size());
          addresses += ':' + emailAddr.get(i).Email;
      }
             
        System.Debug('Admin EMail Address' + addresses);      
        String[] toAddresses = addresses.split(':', 0);       
        mail.setToAddresses(toAddresses);      

        mail.setHtmlBody('Test mail');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        return null;
       
    }
}

1 comment:

  1. This is great. However these are internal users so we can leverage "setTargetObjectId" , so it will by pass the maximum outbound email limits .

    ReplyDelete