我知道这个问题很久以前就被问过了,但我想我会在这里放弃 2020 年的答案,以便它可以潜在地帮助新访客。
请注意:
- 此答案作为通用答案,将要求您根据您使用的表单输入编辑一些详细信息。
- 您还需要将标题等中的电子邮件地址更新为连接到您的域的电子邮件地址。
- 此解决方案假定您使用的是 Google Recaptcha。如果没有,那么只需删除有关“Google recapthca”的部分。
- 此脚本添加了不应删除的安全性和验证。
- 如果您要使用Sweet Alert,那么您应该通过CDN 或 NPM将其安装到您的网站/应用程序中。
一些用于创建在邮件发送时触发的自定义Sweet Alert警报的 Javascript:
// Custom SweetAlert alert that gets triggered on email send
function enquirySent() {
swal({
title: "Email sent!",
text: "Thank you for your email. We'll be in contact ASAP.",
icon: "success",
button: "Okay",
});
}
function enquiryNotSent() {
swal({
title: "Oops!",
text: "Your email was NOT sent due to an error.",
icon: "error",
button: "Okay",
});
};
发送邮件的 PHP 脚本:
<?php
if (isset($_POST['submit'])) {
// For the Google recaptcha
$curlx = curl_init();
curl_setopt($curlx, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curlx, CURLOPT_HEADER, 0);
curl_setopt($curlx, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlx, CURLOPT_POST, 1);
$post_data = [
'secret' => 'YOUR CAPTCHA SECRET KEY',
'response' => $_POST['g-recaptcha-response']
];
curl_setopt($curlx, CURLOPT_POSTFIELDS, $post_data);
$resp = json_decode(curl_exec($curlx));
curl_close($curlx);
// Google recaptcha end
// Form details (sanitized)
$name = htmlspecialchars($_POST['name']);
$surname = htmlspecialchars($_POST['surname']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// Mail headers and details
$email_from = 'youremail@yourdomain.com';
$email_body = "You have received a new message from the user $name $surname.\nHere is the message:\n\n".$message;
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: ".$email."\r\n";
$headers .= "Return-Path: ".$email."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
$error = false;
// Some more input validation/sanitizing
if (!preg_match("/^[a-zA-Z ]*$/",$first_name) && $first_name!="") {
$error = true;
}
if (!preg_match("/^[a-zA-Z ]*$/",$last_name) && $last_name!="") {
$error = true;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL) && $email!="") {
$error = true;
}
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;
}
}
if (IsInjected($visitor_email)) {
echo "Bad email value!";
exit;
}
// Sending the email
if ($error == false) {
$to = "youremail@yourdomain.com";
$subject = "Enquiry from website";
mail($to, $subject, $email_body, $headers);
// Calling the email sent / not sent alerts
echo '<script type="text/javascript">',
'enquirySent()',
'</script>';
} else {
echo '<script type="text/javascript">',
'enquiryNotSent()',
'</script>';
}
}
?>