用php发送电子邮件

用php发送电子邮件,php,Php,您好,我已经用php验证了一个表单,但代码中似乎有错误。验证后应该发送一封电子邮件,但没有。这是我的代码: $firstName = $_POST["firstName"]; $lastName = $_POST["lastName"]; $email = $_POST["email"]; $message = $_POST["message"]; $to = "fox.team001@gmail.com"; $subject = $firstName . " " . $lastName;

您好,我已经用php验证了一个表单,但代码中似乎有错误。验证后应该发送一封电子邮件,但没有。这是我的代码:

  $firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$email = $_POST["email"];
$message = $_POST["message"];
$to = "fox.team001@gmail.com";
$subject = $firstName . " " . $lastName;
$headers = "From: fox.team001@gmail.com\r\nReply-To: fox.team001@gmail.com";

validate($firstName , $lastName , $email , $message);

function validate ($firstName , $lastName , $email , $message){
    if(!empty($firstName) && !empty($lastName)  && !empty($email) && !empty($message)){
        if(validateEmail($email)){
            $mail_sent = @mail($to , $subject , $message , $headers);
            header('refresh:5;url=http://www.foxteam.net');
        }else{
           header('refresh:0;url=http://www.foxteam.net/contact.php');
        }
    }else{
        header('refresh:0;url=http://www.foxteam.net/contact.php');
    }
}

function validateEmail($email) {
    $pattern = "^[A-Za-z0-9_\-\.]+\@[A-Za-z0-9_\-]+\.[A-Za-z0-9]+$";
    if(preg_match("/{$pattern}/", $email)) {
        return true;
    }else{
        return false;
    }
}

您需要将
$to
$headers
作为函数的参数-它们超出了函数的范围,因此它无法看到它们。

您查看了邮件服务器的错误日志吗?您的电子邮件是否已进入垃圾邮件文件夹?您是否尝试过使用相同的代码向不同电子邮件提供商的地址发送一封非常基本的电子邮件(没有额外的标题)?您是否确定所有的
$\u POST
字段都已填充?是的,所有字段都已填充。我还建议使用类似Swiftmailer()的库来发送电子邮件。许多电子邮件客户端倾向于将内部php函数发送的电子邮件归类为垃圾邮件。这应该是一条注释。请删除不客气。虽然如果你没有提到,我从来没有见过它,但是如果你把它从函数中去掉,代码工作得很好。
function validate ($firstName , $lastName , $email , $message){
    if(!empty($firstName) && !empty($lastName)  && !empty($email) && !empty($message)){
        if(validateEmail($email)){
            $mail_sent = @mail($to , $subject , $message , $headers);
            header('refresh:5;url=http://www.foxteam.net');
        }else{
           header('refresh:0;url=http://www.foxteam.net/contact.php');
        }
    }else{
        header('refresh:0;url=http://www.foxteam.net/contact.php');
    }
}