How to send form data to mail in php

To send form data to an email using PHP, you can use the mail() function or a PHP mail library like PHPMailer. Here's an example of how to do it using the mail() function:

Example 1: Using the mail() function

<?php
// Get the form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Set the email address and subject
$to = '[email protected]';
$subject = 'Contact Form Submission';

// Set the email body
$body = "Name: $name\n";
$body.= "Email: $email\n";
$body.= "Message: $message";

// Send the email
mail($to, $subject, $body, 'From: Your Name <[email protected]>');

// Check if the email was sent successfully
if (mail($to, $subject, $body, 'From: Your Name <[email protected]>')) {
    echo 'Email sent successfully!';
} else {
    echo 'Error sending email!';
}
?>

In this example, we're using the mail() function to send an email to the specified address with the form data as the email body. The mail() function takes four arguments: the recipient's email address, the subject of the email, the email body, and the sender's email address.

Example 2: Using PHPMailer

<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

// Get the form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Create a new PHPMailer object
$mail = new PHPMailer\PHPMailer\PHPMailer();

// Set the email address and subject
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]');
$mail->Subject = 'Contact Form Submission';

// Set the email body
$mail->Body = "Name: $name\n";
$mail->Body.= "Email: $email\n";
$mail->Body.= "Message: $message";

// Send the email
if (!$mail->send()) {
    echo 'Error sending email!';
} else {
    echo 'Email sent successfully!';
}
?>

In this example, we're using the PHPMailer library to send an email to the specified address with the form data as the email body. We're creating a new PHPMailer object, setting the email address and subject, and then sending the email using the send() method.

Security Note

When sending form data to an email using PHP, it's important to validate and sanitize the data to prevent potential security vulnerabilities. You should always use prepared statements and parameterized queries to prevent SQL injection attacks, and you should also validate and sanitize the form data to prevent cross-site scripting (XSS) attacks.

Additionally, you should consider using a secure method of sending emails, such as using a secure SMTP server or a third-party email service like Sendgrid or Mailgun.