joey942 joey942 - 1 year ago 95
PHP Question

HTML and PHP Code Not Sending Email

I've been trying to send an email using PHP, and I've found this code that suits my needs as it will easily fit into my current website's code. However, I put this entire code into a file and tested it out, and it won't send the email.


$to = ""; // this is your Email address
$from = $_POST['email']; // this is 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($from,$subject2,$message2,$headers2); // sends a copy of the message 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 another page.

<!DOCTYPE html>
<title>Form submission</title>

<form action="" 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">


I am unable to get this to send an email to "". Am I doing something wrong, or did I forgot to fill something out?

Answer Source

As, you are using it locally, and your mail server is not configured:

You can configure Gmail SMTP for that to work like this:

// Pear Mail Library
require_once "Mail.php";

$from = '<>';
$to = '<>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject

$smtp = Mail::factory('smtp', array(
        'host' => 'ssl://',
        'port' => '465',
        'auth' => true,
        'username' => '',
        'password' => 'passwordxxx'

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo('<p>' . $mail->getMessage() . '</p>');
} else {
    echo('<p>Message successfully sent!</p>');

It also occurs sometimes that either your sender email or recipient email should be an email that is configured on your website's mail server or cPanel. Due to security reasons, most hosting service providers do not allow this thing. Change it to an email address which is configured on your website's mail server, it should work then.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download