我有一个问题与PHP邮件。每次页面加载时,它都会发送一个空白的电子邮件。
我相信这是一个简单的东西(也许缺少一个条件,如果提交按钮被击中)来解决这个问题。
他们的文档似乎没有一个虽然和脚本第一次工作时,我第一次使用它,但然后开始发送电子邮件在页面加载后的前几次。谢谢!
<form method="post" action="">
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Enter Name">
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" placeholder="Enter Email">
</div>
<div class="form-group">
<input name="subject" type="text" class="form-control" placeholder="Enter Subject">
</div>
<div class="form-group">
<textarea name="message" class="form-control" rows="5" placeholder="Enter Message"></textarea>
</div>
<button name="submit" type="submit" value="submit" class="btn btn-submit">Submit</button>
</form>
<?php
require '/phpmailer/PHPMailerAutoload.php';
require_once('/phpmailer/class.phpmailer.php');
include("/phpmailer/class.smtp.php");
$emailaddress = 'info@newpointdigital.com';
$message=
'Name: '.$_POST['name'].'<br />
Email: '.$_POST['email'].'<br />
Subject: '.$_POST['subject'].'<br />
IP: '.$_SERVER['REMOTE_ADDR'].'<br /><br />
Message:<br /><br />
'.nl2br($_POST['message']).'
';
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "smtp.gmail.com"; // SMTP server
//$mail->SMTPDebug = 2; // 1 = errors and messages,2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.gmail.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "info@newpointdigital.com"; // SMTP account username (the email account your created)
$mail->Password = "newpoint!@#$"; // SMTP account password (the password for the above email account)
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->CharSet = 'UTF-8'; // so it interprets foreign characters
$mail->SetFrom($_POST['email']);
$mail->AddReplyTo($_POST['email']);
$mail->Subject = "Contact form from ".$_POST['name']." ";
$mail->MsgHTML($message);
$mail->AddAddress($emailaddress);
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>
您不检查是否发生了表单提交。你只需在页面加载时调用你的电子邮件代码。有几种方法可以确定是否发生了表单提交。一种方法是检查表单操作是否为POST:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// email code goes here
}
你也可以检查提交按钮是否被按下:
if (isset($_POST['submit'])) {
// email code goes here
}
其他需要知道的事情:
- 你不做任何数据验证,所以仍然有可能有人没有提交任何内容,导致发送空白电子邮件
- 你没有防止头注入,这使得你的表单容易发送垃圾邮件
这是因为你没有为它的运行应用任何条件,所以代码在页面加载时逐行运行。
所以保持你的邮件发送代码在提交检查条件下,这样它会在提交后运行,点击
if(isset($_POST['submit'])) {
// your mail sending code
}
或使用您的任何帖子数据,如电子邮件检查
if(!empty($_POST['email'])) {
// your mail sending code
}