How to pass select value using php mail
When sending a PHP mail, you can pass the selected value from a dropdown select box to the email body using the $_POST
or $_GET
superglobals.
Here's an example:
HTML
<form action="send_email.php" method="post">
<select name="my_select">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<input type="submit" value="Send Email">
</form>
PHP (send_email.php)
<?php
// Get the selected value from the form
$selected_value = $_POST['my_select'];
// Set the email body
$email_body = "You selected: $selected_value";
// Set the email headers
$to = "[email protected]";
$subject = "Selected Value";
// Send the email
$headers = "From: [email protected]";
mail($to, $subject, $email_body, $headers);
?>
In this example, when the form is submitted, the selected value from the dropdown select box is passed to the send_email.php
script using the $_POST
superglobal. The script then uses this value to set the email body and sends the email using the mail()
function.
You can also use $_GET
instead of $_POST
if you're using a GET request instead of a POST request.
Alternatively, you can use a PHP library like PHPMailer to send emails, which provides a more robust and flexible way to send emails. Here's an example:
<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$selected_value = $_POST['my_select'];
$email_body = "You selected: $selected_value";
$mail->setFrom('[email protected]');
$mail->addAddress('[email protected]');
$mail->Subject = "Selected Value";
$mail->Body = $email_body;
if (!$mail->send()) {
echo 'Error sending email';
} else {
echo 'Email sent successfully';
}
?>
Make sure to install the PHPMailer library and configure it according to your email server settings.