PHP发送电子邮件多次发送电子邮件

时间:2017-01-23 14:15:32

标签: php session html-form

我有一个脚本发送一封电子邮件,其中包含存储在会话中的信息 - 该信息是从用户填写的表单中收集的。 (表单'action'指向下面的代码)

但是,例如,当在表单上单击两次提交按钮时,会发送2封电子邮件,当点击3次时,会发送3封电子邮件。

我想确保只发送一封电子邮件,如果任何会话为空,则不会发送电子邮件:

<?php

session_start();

if(isset($_POST['email'])) {

$email_to = "recipient@emailaddress.com";
$email_subject = "My Subject";


$machine = implode(",", $_SESSION['machinesesh']); //required 
$machine_type = implode(" ", $_SESSION['typesesh']);; // required
$address = $_SESSION['addresssesh']; //required
$county = $_SESSION['countysesh']; //required
$postcode = $_SESSION['postcodesesh']; //required
$workplace = implode(', ', $_SESSION['worksesh']); //required
$serving = implode(', ', $_SESSION['peoplesesh']);
$company_name = $_SESSION['namesesh']; // required
$visitorname = $_POST['yourname']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required


$email_message = "New email alert .\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "Name: ".clean_string($visitorname)."\n";
$email_message .= "Company: ".clean_string($company_name)."\n";
$email_message .= "Address Line 1: ".clean_string($address)."\n";
$email_message .= "County: ".clean_string($county)."\n";
$email_message .= "Postcode: ".clean_string($postcode)."\n";
$email_message .= "Machine(s) Wanted: ".clean_string($machine)."\n";
$email_message .= "Environment: ".clean_string($workplace)."\n";
$email_message .= "Serving: ".clean_string($serving)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";


// create email headers
$headers = 'From: sendaddress@email.com' . "\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers); 

header("Location: http://www.example.com?tag=$machine");

?>

2 个答案:

答案 0 :(得分:0)

如何设置$ _SESSION [&#34; emailsent&#34;] = 1; ?在发送电子邮件之前,请检查变量是否存在以及是否设置为1!在这种情况下,您知道,在此会话中,电子邮件只发送一次!

答案 1 :(得分:0)

发送电子邮件后,您可以尝试删除会话。下次提交表单时,应检查是否设置了会话值。如果未设置,则不应再次发送电子邮件。