Home >Backend Development >PHP Tutorial >How to Send Emails Using PHP from an HTML Form?

How to Send Emails Using PHP from an HTML Form?

Linda Hamilton
Linda HamiltonOriginal
2025-01-01 12:00:20905browse

How to Send Emails Using PHP from an HTML Form?

Send an Email with PHP from HTML Form

Front-End HTML Code

Copy and paste the following code into your HTML form:

<form action="mail_handler.php" method="post">
  First Name: <input type="text" name="first_name"><br>
  Last Name: <input type="text" name="last_name"><br>
  Email: <input type="text" name="email"><br>
  Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
  <input type="submit" name="submit" value="Submit">
</form>

Back-End PHP Code

Copy and paste the following code into your PHP handler (mail_handler.php):

<?php
if (isset($_POST['submit'])) {
  $to = "[email protected]"; // Replace with your email address
  $from = $_POST['email']; // Fetching the sender's email address
  $first_name = $_POST['first_name'];
  $last_name = $_POST['last_name'];
  $subject = "Form Submission";
  $subject2 = "Copy of Your Form Submission";
  $message = $first_name . " " . $last_name . " wrote the following:\n\n" . $_POST['message'];
  $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

  $headers = "From: $from";
  $headers2 = "From: $to";
  mail($to, $subject, $message, $headers);
  mail($from, $subject2, $message2, $headers2); // Send a copy to the sender
  echo "Mail Sent. Thank you $first_name, we will contact you shortly.";
  // You can also use header('Location: thank_you.php'); to redirect to a thank you page.
}
?>

Sending HTML Emails

If you wish to send HTML emails, create separate HTML headers with distinct variable names. Refer to the PHP mail() manual for details.

Troubleshooting

If you encounter issues sending emails, refer to this Stack Overflow question and answer: https://stackoverflow.com/questions/13061936/php-mail-form-doesnt-complete-sending-e-mail

The above is the detailed content of How to Send Emails Using PHP from an HTML Form?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn