This is how to make a PHP contact form with options that send to different email recipients. I will write it again for the Google searchers out there. This is how to make a PHP contact form that sends emails to different recipients based on options selected.
This is not a beginners course. This is meant to help anyone out there that has an intermediate understanding of Html and PHP.
Great, let’s get started.
First the easy part is to write the html. This form will have a drop down menu with five options and a field for a return email address. You can add any fields you like just be sure to give them a reference for the php code.
<form method=”post” name=”email_form”
<label for=”select”>Select an option</label>
<select name=”department” id=”select” size=”5″>
<option value=”department2″ id=”design”>department2</option>
<option value=”department3″ id=”quality”>department3</option>
<option value=”other” >Other</option>
<input type=”text” name=”email” />
<button type=”submit” name=”submit”>Submit</button>
This is a simple form with no bells and whistles. Next is the PHP part of the form. Create a new document. Call it mailform.php. Beleow is the PHP that will go into the document. You can call it whatever you like just be sure that the action in the Html above is linked right.
//THIS SWITCH STATEMENT CORRESPONDS WITH YOUR HTML OPTIONS.
//WHATEVER OPTION THE USER SELECTS IN THE HTML PART TURNS ON
//ONE OF THE BELOW LINES OF OF CODE.
case “department1″: $my_email = ‘email@example.com'; break;
case “department2″: $my_email = ‘firstname.lastname@example.org'; break;
case “department3″: $my_email = ‘email@example.com'; break;
case “department4″: $my_email = ‘firstname.lastname@example.org'; break;
case “OTHER”: $my_email = ‘email@example.com'; break;
//THIS LINE USES WHATEVER IS TURNED ON ABOVE
//TO KNOW WHICH EMAIL TO SEND TO
$email_to = $my_email;
//EMAIL_SUBJECT IS EMAIL SUBJECT
$email_subject = “Your email subject line”;
//EMAIL IS THE RETURN EMAIL ENTERED IN HTML.
$email = $_POST[’email’];
//DEPARTMENT IS THE SUM OF ALL YOUR CASES.
//ONLY THE OPTION SELECT WILL BE SEEN
$department = $_POST[‘department’];
//EMAIL_MESSEGE TURNS THE OPTION SELECT INTO A STRING
//AND DISPLAYS IT IN THE EMAIL
$email_message = “Option Selected: “.clean_string($department).”n”;
//THIS SENDS THE EMAIL
$headers = ‘From: ‘.$email.”rn”.
‘Reply-To: ‘.$email.”rn” .
‘X-Mailer: PHP/’ . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
//THIS WILL REDIRECT THE USE TO A LANDING PAGE
header( ‘Location: http://www.mysite/success.html’ ) ;
The important piece of code that makes the options work is the SWITCH. Without it you would have a basic contact form that only sends to a single email. You can see how this may be useful if you have several contacts but only one contact form.
I glossed over a lot of the specific details so if you need any help don’t hesitate to contact me.
Sr. Web Developer, Tranquilblue
May 20, 2013