-2

I'm trying to make a very basic contact form in PHP. I'm using MAMP to test it. For some reason, however, the form doesn't work: when I fill in the form and press the "submit" button, I am redirected to index.html?mailsend but I don't receive any email! What am I doing wrong?

my HTML code:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="contactform.php" method="POST">
        <input type="text" name="name" placeholder="Full Name">
        <input type="text" name="mail" placeholder="Your e-mail">
        <input type="text" name="subject" placeholder="Subject">
        <textarea name="message" placeholder="Message"></textarea>
        <button type="submit" name="submit">Send e-mail</button>
    </form>

</body>
</html>

my PHP code:

if (isset($_POST['submit'])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$mailFrom = $_POST['mail'];
$message = $_POST['message'];


$mailTo = "tomms1998@gmail.com";
$headers = "From: ".$mailFrom;
$txt = "You have received an e-mail from ".$name.".\n\n".$message;

mail($mailTo, $subject, $txt, $headers);
header("Location: index.html?mailsend");
}

?>
tommsyeah
  • 17
  • 2
  • 9

1 Answers1

-1

You have to configure SMTP on your server. You can use G Suite SMTP by Google for free:

<?php

$mail = new PHPMailer(true);

// Send mail using Gmail
if($send_using_gmail){
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->SMTPAuth = true; // enable SMTP authentication
    $mail->SMTPSecure = "ssl"; // sets the prefix to the servier
    $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
    $mail->Port = 465; // set the SMTP port for the GMAIL server
    $mail->Username = "your-gmail-account@gmail.com"; // GMAIL username
    $mail->Password = "your-gmail-password"; // GMAIL password
}

// Typical mail data
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $name_from);
$mail->Subject = "My Subject";
$mail->Body = "Mail contents";

try{
    $mail->Send();
    echo "Success!";
} catch(Exception $e){
    // Something went bad
    echo "Fail :(";
}

?>
vikalp
  • 330
  • 2
  • 9
  • Thank you for your help. I tried your code but for some reason it doesn't work.. Now that I know that the function mail() won't work in localhost I wonder: if I were to host the website online, would my code work? – tommsyeah Mar 21 '18 at 09:27
  • @tommsyeah Yes on the live server you code will work. – vikalp Mar 22 '18 at 06:36