【问题标题】:PHP contact form issuePHP联系表格问题
【发布时间】:2011-05-27 17:51:50
【问题描述】:

我在使用简单的 PHP 联系表单时遇到问题。我发送表单时没有遇到任何错误,但没有任何内容发送到我的电子邮件。 任何帮助将不胜感激。

这是 HTML

    <form method="POST" name="contactform" action="contact-form-handler.php"> 
    <p>
    <label for='name'>Your Name:</label> <br>
    <input type="text" name="name">
    </p>
    <p>
    <label for='email'>Email Address:</label> <br>
    <input type="text" name="email"> <br>
    </p>
    <p>
    <label for='message'>Message:</label> <br>
    <textarea name="message"></textarea>
    </p>
    <input type="submit" value="Submit"><br>
    </form>

还有 PHP

    <?php 
    $errors = '';
    $myemail = 'name@website.com';//<-----Put Your email address here.
    if(empty($_POST['name'])  || 
       empty($_POST['email']) || 
       empty($_POST['message']))
    {
        $errors .= "\n Error: all fields are required";
    }

    $name = $_POST['name']; 
    $email_address = $_POST['email']; 
    $message = $_POST['message']; 

    if (!preg_match(
    "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", 
    $email_address))
    {
        $errors .= "\n Error: Invalid email address";
    }

    if( empty($errors))
    {
        $to = $myemail; 
        $email_subject = "Contact form submission: $name";
        $email_body = "You have received a new message. ".
        " Here are the details:\n Name: $name \n Email: $email_address \n Message \n                 $message"; 

$headers = "From: $myemail\n"; 
$headers .= "Reply-To: $email_address";

mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
    } 
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"                         "http://www.w3.org/TR/html4/loose.dtd"> 
    <html>
    <head>
<title>Contact form handler</title>
    </head>

    <body>
    <!-- This page is displayed only if there is some error -->
    <?php
    echo nl2br($errors);
    ?>

【问题讨论】:

    标签: php html forms contact


    【解决方案1】:

    检查底层邮件系统。

    如果您使用的是 Linux 机器,它可能被配置为仅用于本地交付,因此您可以发送电子邮件至 yourusername@yourhostname,它最终会以 /var/mail/yourusername 结尾

    此外,您应该在 Header 调用之后放置一个 exit(),以便在重定向后不发送额外的 HTML。

    【讨论】:

      【解决方案2】:

      对于从 PHP 脚本发送电子邮件,我建议您使用 PHPMailer Class http://phpmailer.worxware.com/

      它很容易实现,也很容易使用。我为您提供了一个示例(对不起西班牙 cmets :)):

      来自: 西班牙语 ▼ 到: 英语 ▼

      // Instantiate an object of the class we call phpmailer
      // For example 
      mail $ mailer = new phpmailer (); 
      // define the properties and call methods 
      // for the mail order
      
      // With PluginDir tells the phpmailer class which 
      // is the class smtp as I mentioned at the beginning of 
      // this example will be in the subdirectory includes 
      $ mailer-> PluginDir = ". /Inc/";
      
      // With the Mailer property we indicate that we will use an SMTP server 
      $ mailer-> Mailer = "smtp";
      
      // Assign to Host the name of our SMTP server 
      $ mail-> Host = "EmailServer.com"
      
      // We tell you which is our username and password 
      $ mail-> Username = "email", $ mail-> Password = "passwd"
      
      // Indicate which is our-n-mail address and name it 
      // we want to see the user who reads our email 
      $ mailer-> From = "senderemail@sender.com" 
      $ mailer-> FromName = "Sender name" ;
      
      // The default Timeout 10, is a bit low because I use 
      // a free account, so I put it to 15
      $ Mailer-> Timeout = 15;
      
      // Indicate which is the destination address of the email 
      $ mailer-> AddAddress ($ this-> destination);
      
      // Assign the message subject and body. The body of the message put in html 
      $ mailer-> Subject = "Subject" 
      $ mailer-> Body = "Body with HTML"
      
      // Define AltBody by mail if the recipient does not support html formatted email 
      $ mailer-> AltBody = "Alternative Body";
      
      // Send the message, if no problems // $ success variable contains the value true 
      $ success = $ mailer-> Send ();
      
      // If the message has not been sent 4 trials be conducted more like a lot 
      // to send the message, every attempt will be made 5 seconds after 
      // the previous one, for it uses the sleep function
      $ Tries = 1; while ((! $ Exit) & & ($ attempts <5)) 
      {
          sleep (4), 
          $ success = $ mailer-> Send (), $ attempts + +;
      }
      
      if (! $ success) 
      {
           echo "Failed to send. Try again later.. 
           $ mailer-> ErrorInfo;} else {echo" Query successfully sent. "
      }
      

      原答案版本--


      //instanciamos un objeto de la clase phpmailer al que llamamos 
      //por ejemplo mail
      $mailer = new phpmailer();
      //Definimos las propiedades y llamamos a los métodos 
      //correspondientes del objeto mail
      
      //Con PluginDir le indicamos a la clase phpmailer donde se 
      //encuentra la clase smtp que como he comentado al principio de 
      //este ejemplo va a estar en el subdirectorio includes
      $mailer->PluginDir = "./inc/";
      
      //Con la propiedad Mailer le indicamos que vamos a usar un servidor smtp
      $mailer->Mailer = "smtp";
      
      //Asignamos a Host el nombre de nuestro servidor smtp
      $mail->Host = "EmailServer.com";
      
      //Le decimos cual es nuestro nombre de usuario y password
      $mail->Username = "email"; 
      $mail->Password = "passwd";
      
      //Indicamos cual es nuestra direcci—n de correo y el nombre que 
      //queremos que vea el usuario que lee nuestro correo
      $mailer->From = "senderemail@sender.com";
      $mailer->FromName = "Sender name";
      
      //el valor por defecto 10 de Timeout es un poco escaso dado que voy a usar 
      //una cuenta gratuita, por tanto lo pongo a 15  
      $mailer->Timeout=15;
      
      //Indicamos cual es la dirección de destino del correo
      $mailer->AddAddress($this->destino);
      
      //Asignamos asunto y cuerpo del mensaje. El cuerpo del mensaje lo ponemos en formato html
      $mailer->Subject = "Subject"
      $mailer->Body = "Body with HTML";
      
      //Definimos AltBody por si el destinatario del correo no admite email con formato html 
      $mailer->AltBody = "Alternative Body";
      
      //se envia el mensaje, si no ha habido problemas 
      //la variable $exito tendra el valor true
      $exito = $mailer->Send();
      
      //Si el mensaje no ha podido ser enviado se realizaran 4 intentos mas como mucho 
      //para intentar enviar el mensaje, cada intento se hara 5 segundos despues 
      //del anterior, para ello se usa la funcion sleep   
      $intentos=1; 
      while ((!$exito) && ($intentos < 5)) {
           sleep(4);
           $exito = $mailer->Send();
           $intentos++;   
      }
      
      if(!$exito){
           echo "Error al enviar. Intentelo de nuevo mas tarde. ".$mailer->ErrorInfo; }else{
           echo "Consulta enviada correctamente.";
      }
      

      【讨论】:

        【解决方案3】:

        如果您正在拨打mail 电话,那么您的所有输入都是好的。注意mail 返回一个布尔值也很有用,因此您可以执行以下操作:

        if (mail($to, $email_subject, $email_body, $headers))
        {
            //redirect to the 'thank you' page
            header('Location: contact-form-thank-you.html');
        }
        else
        {
            $errors .= "\n" . 'Mail environment failure.';
        }
        

        如果您看到该错误,则表示 mail 未在 php.ini 中正确配置。有关您需要在 php.ini 中设置的值的更多信息,请参阅这篇文章:http://www.techrepublic.com/article/a-tour-of-the-phpini-configuration-file-part-2/5272345

        【讨论】:

          【解决方案4】:

          我认为这可能是电子邮件标题的问题。从规范来看,标题和实际内容之间应该有新的一行。

          $headers .= "Reply-To: $email_address\r\n"; 它可能会有所帮助。

          【讨论】:

          • 我很确定这不是必需的。 mail() 函数会自行插入。
          • 嗯,这是一个猜测,可以解决它。我个人使用这个,从来没有遇到过问题。这并不意味着我做错了或做更多需要做的事情。这个问题可能在任何地方。邮件服务器收不到邮件。错误地将 php 设置为 smtp 服务器....
          猜你喜欢
          • 2013-08-15
          • 2016-06-23
          • 2015-06-22
          • 2013-11-02
          • 2016-02-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多