2013-07-31 110 views
0

我的网站是HTML5。因此,我的文件是.html。我有一个contact.html文件,我想用它来发送消息,使用PHP。我没有太多的PHP经验(所以如果有人可以推荐一个更好的选择,非.NET的方式发送电子邮件,请让我知道)。如何在HTML文件中通过PHP发送电子邮件?

我最初的想法是将我的PHP代码包含在我的HTML文件中(不管这是否可能,甚至不建议,我不知道)。我之前完成了一次,我相信我记得有一个form标记,它的某个属性指定了我用来发送电子邮件的.php文件。

类似于<form someattribute="sendmail.php"> ... </form>

问题:鉴于我THINK我应该做的(上图),这是最好的办法(指定我的表单标签里面的PHP文件),或者你推荐一个更好的方法来从原始发送电子邮件.html文件?

+0

你打算做是正确的方式。将表单提交给PhP脚本,处理该PhP脚本中的POST变量并发送邮件,然后重定向至确认页面。 –

+0

Someattribute应该是action ='sendmail.php'和你的正确轨道。 – jeff

+0

不要忘记表单中的action ='post'属性。 – notknown7777

回答

5

你不能只使用HTML。如果你坚持到PHP的解决方案,尝试

<?php 
    if(isset($_POST['send'])) //check the submit button was pressed 
    { 
     //get variables from POST array. Remember we specified POST method 
     $to = $_POST['to']; 
     $subject = $_POST['subject']; 
     $message = $_POST['message']; 

     //set up headers 
     $headers = 'From: [email protected]' . "\r\n" . 
        'Reply-To: [email protected]' . "\r\n" . 
        'X-Mailer: PHP/' . phpversion(); 

     //send the email and save the result 
     $result = mail($to, $subject, $message, $headers); 

     //was it sent? 
     if($result) 
     { 
      echo "Successfuly sent the email"; 
     } 
     else 
     { 
      echo "An error has occured"; 
     } 
    } 
?> 
<hr> 
<form method="POST"> 
    To: <input type="text" name="to"> <br> 
    Subject: <input type="text" name="subject"> <br> 
    Text: <textarea name="message"></textarea><br> 
    <input type="submit" value="Send" name="send"> 
</form> 

你并不需要指定的形式分,因为这是同一个文件。否则,这将是

<form action="somefile.php" method="POST"> 

Altough必须指定POST方法,否则所有的数据将通过GET默认发送

PHP有用来发送电子邮件邮件功能http://php.net/manual/en/function.mail.php

如果邮件已成功接收传送,则返回TRUE,否则返回FALSE 。

我们检查电子邮件是否被发送并打印相应的消息。然后,不管结果如何,我们都会打印出消息表单。

+1

你错过了'行动'。 –

+0

如果它是相同的文件,那么它是不需要的。但感谢指出,我编辑了答案 –

+0

我没有一个“action”属性指定我的PHP脚本吗? –

2

您可以轻松地将数据发布到一个PHP文件发送邮件。只需要编写一些代码,该php文件和表单用户action ='phpfilename.php'。就是这样。

2

如果您只是试图通过电子邮件发送表单信息,它非常简单。

<form action="sendmail.php"> 

只是需要确保你的编码正确的PHP文件。

2

http://php.net/manual/en/function.mail.php

mail。HTML

<form action="mail.php" method="post"> 
    To <input type="text" name="to"/><br/> 
    Subject <input type="text" name="subject"/><br/> 
    Message <textarea name="message"></textarea><br/> 
    <input type="submit" value="Send"/> 
</form> 

mail.php

<?php 
    mail($_POST["to"] , $_POST["subject"], $_POST["message"]); 
    header("Location: mail.html"); //redirect the user 
?> 
+0

不应该“方法”是POST? –

+0

它可以是任何你想要的。但我会推荐帖子。编辑制作。 –

相关问题