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
Nagma KhanNagma Khan 

how to send the email to all contact person with the visualforce page in salesforce?

hi

i want to send a email to all contact person and showing all contact details on the visualfroce and want to send the email to all contact person just clicking button sending email


Thanks
Nagma khan
Best Answer chosen by Nagma Khan
Maharajan CMaharajan C
Hi Nagma,

Please try the below Code which works fine to me!!!

VF Page:

<apex:page controller="ContactList">
    <apex:form >   
    <apex:pageBlock >
        <apex:pageBlockTable value="{!Lstwrp}" var="w">
            <apex:column value="{!w.acc.Id}" headerValue="Contact Id"/>
            <apex:column value="{!w.acc.Name}" headerValue="Contact Name"/>
            <apex:column value="{!w.acc.Email}" headerValue="Email"/>
                   </apex:pageblockTable>
          <apex:pageBlockButtons >
        <apex:commandButton value="Send Email" action="{!selected}"/>
        </apex:pageBlockButtons>
       </apex:pageBlock>
</apex:form>
</apex:page>
            
 
Apex Class:


Public class ContactList
{
public List<wrapperAccountCheckBox> Lstwrp{get;set;}

public ContactList()
{
Lstwrp = new List<wrapperAccountCheckBox>();
List<Contact> accLst=new List<contact>([SELECT Id,Name,Email FROM contact  where name='raj']);
for(integer i=0;i<acclst.size();i++) 
{
Lstwrp.add(new wrapperAccountCheckBox(accLst[i]));
}}

 List<String> selectedlst = new List<String>();
     public void selected(){
          System.debug('---------->'+Lstwrp);
          for(wrapperAccountCheckBox w:Lstwrp){
                  System.debug('---------->'+w.acc);
                  selectedlst.add(w.acc.Email);
                                                 
                                             }
  
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  mail.setSubject('Morning Wishes');
  mail.setPlainTextBody('Good Morning');
  mail.setToAddresses(selectedlst);
  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });  
                                            }


//---------------------------
Public class wrapperAccountCheckBox
{
        
        public contact acc{get;set;}
        
        public wrapperAccountCheckBox(contact a)
        {
           
            this.acc=a;
        }
        
        }
//----------------------------
}


Can you please try the code and let me know if it works or not?

Mark this as solved if it's resolved.

Thanks,
Raj

All Answers

NagendraNagendra (Salesforce Developers) 
Hi Nagma,

It is possible to send email using Visualforce by creating a custom controller to deliver the message. The Apex Messaging.SingleEmailMessage class handles the outbound email functionality available to Salesforce.
The following topics demonstrate a number of features available when sending email through Visualforce: May I also suggest you please try the below code snippet which might help.

Visual Force Page:
<apex:page controller="sendEmail">
    <apex:messages />
    <apex:pageBlock title="Send an Email to Your {!account.name} Representatives">
        <p>Fill out the fields below to test how you might send an email to a user.</p>
 
        <apex:dataTable value="{!account.Contacts}" var="contact" border="1">
            <apex:column >
                <apex:facet name="header">Name</apex:facet>
                {!contact.Name}</apex:column>
            <apex:column >
                <apex:facet name="header">Email</apex:facet>
                {!contact.Email}</apex:column>
        </apex:dataTable>
   
        <apex:form ><br/><br/>
            <apex:outputLabel value="Subject" for="Subject"/>: <br/>    
            <apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
            <br/><br/>
 
            <apex:outputLabel value="Body" for="Body"/>: <br/>    
            <apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/>          
            <br/><br/>
 
            <apex:commandButton value="Send Email" action="{!send}"/>
        </apex:form>
    </apex:pageBlock>
 
    <apex:pageBlock title="Preview the Attachment for {!account.name}">
        <c:attachment />
    </apex:pageBlock></apex:page>
Apex controller:
public class sendEmail {
    public String subject {get; set;}
    public String body { get; set; }
 
    private final Account account;
 
    // Create a constructor that populates the Account object
   
    public sendEmail() {
        account = [SELECT Name,
                  (SELECT Contact.Name, Contact.Email FROM Account.Contacts)
                   FROM Account
                   WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    }
 
    public Account getAccount() {
        return account;
    }
 
    public PageReference send() {
        // Define the email
   
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
       
 
        // Reference the attachment page and pass in the account ID
       
        PageReference pdf =  Page.EmailAttachment;
         Blob b = pdf.getContent();
        System.debug('____________________________Pdf___________________________'+pdf);
        pdf.getParameters().put('id',(String)account.id);
        pdf.setRedirect(true);
 
     
        System.debug('____________________________Blob___________________________'+b);
 
        // Create the email attachment
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('attachment.pdf');
        efa.setBody(b);
 
        String addresses;
        if (account.Contacts[0].Email != null) {
            addresses = account.Contacts[0].Email;
            // Loop through the whole list of contacts and their emails
   
            for (Integer i = 1; i < account.Contacts.size(); i++) {
                if (account.Contacts[i].Email != null) {
                    addresses += ':' + account.Contacts[i].Email;
                }
            }
        }
 
        String[] toAddresses = addresses.split(':', 0);
 
        // Sets the paramaters of the email
   
        email.setSubject( subject );
        email.setToAddresses( toAddresses );
        email.setPlainTextBody( body );
 
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});// Sends the email
   
        Messaging.SendEmailResult [] r =
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});  
       
        return null;
    }
}
When you will run this code then first of all you will pass "Account Id" into URL.

Please let us know if this helps.

Mark this as solved if it's resolved.

Thanks,
Nagendra.


 
Nagma KhanNagma Khan
hi Nagendra

its showing  erroe
Visualforce Error
Help for this Page
System.QueryException: List has no rows for assignment to SObject
Class.sendEmails.<init>: line 10, column 1


thanks
Nagma
Maharajan CMaharajan C
Hi Nagma,

Please try the below Code which works fine to me!!!

VF Page:

<apex:page controller="ContactList">
    <apex:form >   
    <apex:pageBlock >
        <apex:pageBlockTable value="{!Lstwrp}" var="w">
            <apex:column value="{!w.acc.Id}" headerValue="Contact Id"/>
            <apex:column value="{!w.acc.Name}" headerValue="Contact Name"/>
            <apex:column value="{!w.acc.Email}" headerValue="Email"/>
                   </apex:pageblockTable>
          <apex:pageBlockButtons >
        <apex:commandButton value="Send Email" action="{!selected}"/>
        </apex:pageBlockButtons>
       </apex:pageBlock>
</apex:form>
</apex:page>
            
 
Apex Class:


Public class ContactList
{
public List<wrapperAccountCheckBox> Lstwrp{get;set;}

public ContactList()
{
Lstwrp = new List<wrapperAccountCheckBox>();
List<Contact> accLst=new List<contact>([SELECT Id,Name,Email FROM contact  where name='raj']);
for(integer i=0;i<acclst.size();i++) 
{
Lstwrp.add(new wrapperAccountCheckBox(accLst[i]));
}}

 List<String> selectedlst = new List<String>();
     public void selected(){
          System.debug('---------->'+Lstwrp);
          for(wrapperAccountCheckBox w:Lstwrp){
                  System.debug('---------->'+w.acc);
                  selectedlst.add(w.acc.Email);
                                                 
                                             }
  
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  mail.setSubject('Morning Wishes');
  mail.setPlainTextBody('Good Morning');
  mail.setToAddresses(selectedlst);
  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });  
                                            }


//---------------------------
Public class wrapperAccountCheckBox
{
        
        public contact acc{get;set;}
        
        public wrapperAccountCheckBox(contact a)
        {
           
            this.acc=a;
        }
        
        }
//----------------------------
}


Can you please try the code and let me know if it works or not?

Mark this as solved if it's resolved.

Thanks,
Raj
This was selected as the best answer
Nagma KhanNagma Khan
hi Raj

its Error

Visualforce Error
Help for this Page
System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: null: [toAddresses, null]
Error is in expression '{!selected}' in component <apex:commandButton> in page visualfrocepagemail: Class.ContactList.selected: line 27, column 1
Class.ContactList.selected: line 27, column 1



thanks
Nagma
Nagma KhanNagma Khan
hi sorry
your code is right



Thanls