仅发送填写的字段框。如果为空则不发送电子邮件。 php表单发送电子邮件

时间:2013-09-24 16:54:43

标签: php html forms email post

我有这个简单的表格在php中发送电子邮件。发送php代码中这个表单的好处是我不必写出所有字段名称。例如,我不必写这个:

$msg .= "$_POST[ContactName]     Contact Name:     ContactName\n"

在我的代码中,我必须写的是:

foreach ($_POST as $Field=>$Value) { 
$body .= "$Field: $Value\n";

表格目前运作正常。它目前正在发送:

ContactName: name here
BusinessName: business name here
EmailAddress: email@email.com
Email_Confirmation: 
PhoneNumber: 714-555-5555

但是,我希望这种情况发生:如果一个字段留空或者网络用户没有填写某个字段框,那么表单不应该发送该字段。例如:Web用户决定不填写ContactName和/或BusinessName。所以表单应该只发送这种格式:

EmailAddress: email@email.com
Email_Confirmation: 
PhoneNumber: 714-555-5555

注意到没有提到ContactName:和BusinessName:

请帮忙!我会很感激。 -Michelle Ha。

这是php发送代码:

if the Email_Confirmation field is empty
if(isset($_POST['Email_Confirmation']) && $_POST['Email_Confirmation'] == ''){

    // put your email address here
    $youremail = 'bomandty@gmail.com';

    // prepare a "pretty" version of the message
    $body .= "Thank you for your request. We will get back with you soon.";
    $body .= "\n";
    $body .= "\n";
    foreach ($_POST as $Field=>$Value) { 
    $body .= "$Field: $Value\n"; 
    $body .= "\n";
    }

    $CCUser = $_POST['EmailAddress'];

    // Use the submitters email if they supplied one
    // (and it isn't trying to hack your form).
    // Otherwise send from your email address.
    if( $_POST['EmailAddress'] && !preg_match( "/[\r\n]/", $_POST['EmailAddress']) ) {
      $headers = "From: $_POST[EmailAddress]";
    } else {
      $headers = "From: $youremail";
    }

    // finally, send the message
    mail($youremail, 'subject line here', $body, $headers, $CCUser );

}

// otherwise, let the spammer think that they got their message through

2 个答案:

答案 0 :(得分:3)

foreach ($_POST as $Field=>$Value) { 
if($Value != ''){
$body .= "$Field: $Value\n";
}
}

答案 1 :(得分:1)

向你添加检查

if(empty($Value)) continue;

并将表单中的默认值更改为占位符