提交简单表格,循环并发送邮件?

时间:2012-03-29 12:54:27

标签: php jquery ajax

我是一个绝对的PHP n00b,所以我可以使用一些小片段帮助。

我有一个带有几个无线电和输入字段的简单表格。一旦它们全部填满并且用户提交表单,我想通过jQuery AJAX将其提交给PHP文件,该文件遍历请求中的所有表单元素,将它们添加到字符串中,并将该字符串作为电子邮件(带有预定义的主题)到预定义的电子邮件帐户。你会如何在PHP中完成这个简单的任务?

4 个答案:

答案 0 :(得分:1)

您可以执行类似

的操作
<?php
$to = 'asdf@example.com';
$subject = 'website form';
$message= '';
foreach ($_POST as $key => $value)
{
    $message .= $key . ': ' . $value . PHP_EOL;
}
mail($to, $subject, $message);
?>

答案 1 :(得分:0)

// html_file.html
<form action="" method="POST">...</form>

<script>
$("form").on("submit", function()
{
    $.post($(this).attr("action"), $(this).serialize());
});
</script>

// some_php_file.php
<?php
..
foreach ($_POST as $post_field) {} // process posted data
mail(..) //send mail

答案 2 :(得分:0)

$message = '';
$fields_to_place = array('name', 'message', 'phone', 'status');
foreach($fields_to_place as $f)
{
  if(isset($_POST[$f])) $message .= $f.': '.$_POST[$f]."\n";
}

$headers = "From: server@example.tld\r
Reply-To: ".$_POST['email']."\r\n";
mail('recipient@email.com', 'Contact Form', $message, $headers);

答案 3 :(得分:0)

以下脚本可以包含在具有表单的php文件中,或者您可以使用以下代码单独的php文件,必须在表单的action属性中提及php文件

    <?php
    $content= "First Name: ".$_POST['firstname']."\n";
    $content.= "Last Name: ".$_POST['lastname']."\n";   

    $to = "contactsus@test.com" ;               

            $headers .= "MIME-Version: 1.0\n";
            $headers .= "Mailed-By: test.com\n";
            $headers .= "Content-Type: text/HTML; charset=ISO-8859-1\n";            

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

            if(mail($to,'testsubject',$content,$headers)){
            ?>
            <script type="text/javascript">
                    alert("Thank you for contacting us.We will get back to you soon.");
                    window.location.href="index.php";
            </script>
            <?php
            }else{
            ?>
            <script type="text/javascript">
                    alert("mail not sent! Please try after some time!");
                    window.location.href="index.php";
            </script>
            <?php

            }
    ?>

在内容变量($ content)中,您可以添加从表单中发布的字段。在$ to variable中,您可以提到邮件必须发送到的地址。这比使用jquery或AJAX

更简单
相关问题