0

I'm trying to use the mail() function in PHP, but it's not working. I'm wondering if "From:" in the header parameter needs to be an existing e-mail address.

My code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Email Test</title>
</head>
<body>
    <form>
        <input type="text" name="to" placeholder="Reciever">
        <br>
        <br>
        <input type="text" name="subject" placeholder="Subject">
        <br>
        <br>
        <input type="text" name="from" placeholder="sender">
        <br>
        <br>
        <input type="text" name="cc" placeholder="CC">
        <br>
        <br>
        <textarea type="text" name="message" placeholder="Message" rows="15" cols="50"></textarea>
        <br>
        <br>
        <button type="submit" name="submit" value="submit">Send</button>
    </form>
    <br>

<?php

session_start();

if (isset($_GET["submit"]) && $_SESSION["user_id"] > 0) {
    $to = $_GET["to"];
    $subject = $_GET["subject"];
    $message = $_GET["message"];
    $sender = $_GET["sender"];
    $cc = $_GET["cc"];
    $headers = sprintf("From: %s" . "\r\n" .
    "CC: %s", $sender, $cc);

    mail($to, $subject, $message, $headers);

    echo $to."\n".$subject."\n".$message."\n".$headers."\n";
}

?>

</body>
</html>

I tried to get input from the user using the and tags, but that doesn't seem to work. Then, I tried without that input and it still didn't work.

  • You should use a fixed From address which is from the domain your website lives on. Then there's no danger of the email looking like spam or spoofing of someone else's address. It needn't have a mailbox attached to it, but should be from the right domain. If you need to capture the sender's email from the form, you can put that in the body of the email, and/or the reply-to header – ADyson Mar 13 '23 at 18:27
  • Of course after that there may also be other reasons why an email doesn't reach its destination- see the link above for details – ADyson Mar 13 '23 at 18:27

0 Answers0