[SalesForce] How to call apex method from command button on custom visualforce page

I have a method which sends an email with csv attachments. It works fine when I run it from the "execute anonymous window". All I am trying to do for now is have a button on a custom page which calls the method when I click it.

New to apex and visualforce so there could be something obvious I'm doing wrong.

I have a class with a method which takes 3 parameters defined like this:

public class EmailSpreadsheets {

public static void sendMail(String addressInput, String subjectInput, String monthYearInput) {

Visualforce page:

<apex:page controller="EmailSpreadsheets">
  <apex:form >
    <apex:commandButton value="Email Spreadsheets" action="{!sendMail('parameter1', 'paramater2', 'parameter3')}" />
  </apex:form>
</apex:page>

I get this: "Error: Unknown function sendMail. Check spelling"

I've also tried removing the parameters so it is just:

action="{!sendMail}"

Then I get this: "Error: Unknown method 'EmailLeadSpreadsheets.sendMail()'"

Why isn't it recognising my method, and even if it did, where would I put the input parameters?

Best Answer

You can't specify parameters as you would when calling a method directly from Apex Code. Instead, you have to use apex:param, as shown here:

<apex:commandButton action="{!sendEmail}" value="Send Email" reRender="target">
    <apex:param name="addressInput1" assignTo="{!addressInput}" value="param1" />
    <apex:param name="subjectInput1" assignTo="{!subjectInput}" value="param2" />
    <apex:param name="monthYearInput1" assignTo="{!monthYearInput}" value="param3" />
</apex:commandButton>

But, this leads you to your second problem: you still can't directly pass parameters to the method; they have to be variables:

public static String addressInput { get; set; }
public static String subjectInput { get; set; }
public static String monthYearInput { get; set; }

Finally, you can remove the parameters from the function itself:

public static void sendEmail() {
    // Do it here
}