send-mail.php仅在字段存在时发送字段

时间:2014-05-11 03:38:53

标签: php forms email

我有一个表单被发布到send-mail.php表单字段是动态生成的,有时会存在,有时它不存在。我希望收到的电子邮件只包含表单字段(如果存在),如果表单字段不存在,则电子邮件中应该没有任何内容。无论字段是否存在,下面的代码始终表示“null”。有什么想法吗?

$myBlueTextArea = isset($_POST['sender_BlueText']);
if($myBlueTextArea) print 'not null';
if(!$myBlueTextArea) print 'null';

2 个答案:

答案 0 :(得分:0)

我通常如何使用表格的通用处理器。基本上,将表单字段命名为您希望它们在电子邮件中显示的内容,然后根据该字段创建电子邮件。通常我用破折号分隔单词,所以我使用如下内容:

$body = 'You got a form submission! <br />';
foreach($_POST as $name => $value)
{
    $name = preg_replace('/[^a-zA-z0-9]/', '', $name);
    $body .= "<strong> $name </strong>: $value <br />";
}

这样,所有发布的字段都以某种格式化的方式存储在$body变量中,更改标记以满足您的需求。

答案 1 :(得分:0)

以下代码是我解决问题的方法。您可以通过按原样填写表单并将其发送/发送给自己来测试它,然后注释掉Message textarea字段并重新提交表单。当该字段不存在时,表单发送的电子邮件将省略该字段,而不是将消息字段作为空或空等发送。

<?php
if(isset($_POST['submit'])){
    $to = "johndoe@xmail.com"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";

        if(isset($_POST['message'])){
            $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
        }

    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
}
?>

<!DOCTYPE html>
<head>
    <title>Form submission</title>
</head>
<body>

<form action="" method="post">
    First Name: <input type="text" name="first_name"><br>
    Last Name: <input type="text" name="last_name"><br>
    Email: <input type="text" name="email"><br>
    Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
    <input type="submit" name="submit" value="Submit">
</form>

</body>
</html>