使用php和html表单发送电子邮件

时间:2012-04-05 23:26:50

标签: php html webforms html-email

我有一个表单,我想用它来收集用户信息。我有一个PHP获取信息和存储在变量中。当用户单击提交按钮时,表单提交并成功重定向到感谢页面。由于某种原因,我没有按预期收到电子邮件。有人可以解释我做错了什么。

下面是我的HTML和PHP文件。我稍后会添加javascript验证。此刻我只想让表单提交工作。

PHP

<?php

//This page should not be accessed directly. Need to submit the form.
if(!isset($_POST['submit'])){
echo "ERROR. This page cannot be accessed directly";
}

//Variables from the form
$name               = $_POST['fullname'];
$ageGroup           = $_POST['ageGroup'];
$gender             = $_POST['gender'];
$visit              = $_POST['visit'];
$purposeOfVisit     = $_POST['purposeOfVisit'];
$otherReferrer      = $_POST['otherReferrer'];
$member             = $_POST['member'];
$socialMedia        = $_POST['socialMedia'];
$difficulties       = $_POST['difficulties'];
$easeOfUse          = $_POST['easeOfUse'];
$whatDifficulties   = $_POST['whatDifficulties'];
$specialCondition   = $_POST['specialCondition'];
$browser            = $_POST['browser'];
$preferredFormat    = $_POST['preferredFormat'];
$contentsForWebsite = $_POST['contentsForWebsite'];
$oldContents        = $_POST['oldContents'];
$expectations       = $_POST['expectations'];

$message = "Fullname:"; // will compose later

// Compose email
$email_from = "subash.adikari@gmail.com";
$email_subject = "Infinity User Questionnaire";
$email_body = "You have received a new message from the user $name.\n".
"Here is the message:\n $message".

$to = "subash.adhikari@gmail.com";

$headers = "From: $email_from \r\n";

//Send the email!
mail($to,$email_subject,$email_body,$headers);

//done. redirect to thank-you page.
header('Location: thankyou.html');


if(IsInjected($visitor_email))
{
    echo "Bad email value!";
    exit;
}

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
          '(\r+)',
          '(\t+)',
          '(%0A+)',
          '(%0D+)',
          '(%08+)',
          '(%09+)'
          );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?>     

如果需要,可以下载index.php here

非常感谢。

3 个答案:

答案 0 :(得分:3)

由于这是在您的本地计算机上,因此您需要先在mail()中配置php.ini。例如,您可以将其配置为使用ISP的SMTP服务器:

[mail function]
SMTP = smtp.isp.net
smtp_port = 25
sendmail_from = me@isp.net

有关详细信息,请参阅PHP Documentation

编辑:我刚在我的一台服务器上测试了您的代码,并按预期发送了电子邮件。这进一步让我相信你如何配置mail()功能有问题。

答案 1 :(得分:0)

我建议您使用http://phpmailer.worxware.com/中的PHPMailer发送邮件。使用PHPMailer,您可以跟踪错误,以HTML和TEXT发送邮件,更改编码和管理单词warpers。

此外,正如有人所说,你的脚本不会阻止它直接执行,我认为标题必须只用新行字符“\ n”完成,而不是返回“\ r \ n”。

答案 2 :(得分:0)

问题出在我的托管服务上。我不得不给他们打电话,他们为我修好了。