如何从网站上的PHP电子邮件地址指定

时间:2013-08-11 00:15:34

标签: php html forms

我有一个PHP表单。该表单有效,可以通过它发送电子邮件。它看起来不像是将它们从特定的电子邮件地址发送到我希望电子邮件发送到的电子邮件地址(me@olivercrow.com)。

我希望这些电子邮件是从contact@olivercrow.com发送的,我已在下面配置了这些电子邮件。这是PHP:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Contact'; 
$to = 'me@olivercrow.com'; 
$subject = 'Contact - Oliver Crow';

$body = "From: $name\n E-Mail: $email\n Message:\n $message";

if ($_POST['submit']) {              
    if (mail ($to, $subject, $body, $from)) {
        echo '<script type="text/javascript">
                alert("Your message has been sent!");
            </script>';
    } else { 
        echo '<script type="text/javascript">
                alert("Something went wrong, try again.");
            </script>'; 
        }
    }
?>

我已尝试将$更改为contact@olivercrow.com,但这不会更改电子邮件地址。为什么From地址没有设置?

1 个答案:

答案 0 :(得分:1)

第四个参数不是from,而是extra headers。因此,要包含额外的from标头,请执行以下操作:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Contact <contact@olivercrow.com>'; // You can combine name and address
$to = 'me@olivercrow.com'; 
$subject = 'Contact - Oliver Crow';


$body = "From: $name\n E-Mail: $email\n Message:\n $message";

$extraHeaders = 'From:'.$from; // Header field + header field value.

if ($_POST['submit']) {              
    if (mail ($to, $subject, $body, $extraHeaders)) { // Pass the extra headers...
        echo '<script type="text/javascript">
                alert("Your message has been sent!");
            </script>';
    } else { 
        echo '<script type="text/javascript">
                alert("Something went wrong, try again.");
            </script>'; 
    }
}