使用Bootstrap Validator实现联系表单邮件发送的技术问询
Hey there! I see you're using Bootstrap Validator for your contact form and want to add email sending functionality. Let's break this down into front-end tweaks, back-end processing, and the AJAX glue that connects them—no page refreshes required!
第一步:完善前端表单与验证逻辑
First, let's make sure your HTML form is complete (I'll fill in the missing bits from your snippet) and set up Bootstrap Validator correctly:
<form id="homeform" method="POST"> <div class='form-group'> <input type='text' class='form-control' name='name' required placeholder='Full Name'> </div> <div class='form-group'> <input type='text' name='companyname' class='form-control' required placeholder='Company Name'> </div> <div class='form-group'> <input type='email' class='form-control' name='email' required placeholder='Your Email'> </div> <div class='form-group'> <textarea class='form-control' name='message' rows="5" required placeholder='Your Message'></textarea> </div> <button type="submit" class="btn btn-primary">Send Message</button> <!-- 用于显示提交状态 --> <div id="form-feedback" class="mt-3"></div> </form>
Next, initialize Bootstrap Validator and add AJAX to handle form submission without reloading the page. Add this script before your closing </body> tag:
$(document).ready(function() { $('#homeform').bootstrapValidator({ feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { name: { validators: { notEmpty: { message: 'Full Name is required' } } }, companyname: { validators: { notEmpty: { message: 'Company Name is required' } } }, email: { validators: { notEmpty: { message: 'Email is required' }, emailAddress: { message: 'Please enter a valid email address' } } }, message: { validators: { notEmpty: { message: 'Message cannot be empty' }, stringLength: { min: 10, message: 'Message must be at least 10 characters long' } } } } }).on('success.form.bv', function(e) { // 阻止表单默认提交行为 e.preventDefault(); var $form = $(e.target); // 获取验证实例 var bv = $form.data('bootstrapValidator'); // 用AJAX提交表单数据到后端 $.ajax({ url: 'send-email.php', // 后端处理脚本路径 type: 'POST', data: $form.serialize(), success: function(response) { var res = JSON.parse(response); if (res.success) { $('#form-feedback').html('<div class="alert alert-success">Your message has been sent successfully!</div>'); $form[0].reset(); bv.resetForm(); } else { $('#form-feedback').html('<div class="alert alert-danger">Oops! There was an error sending your message. Please try again later.</div>'); } }, error: function() { $('#form-feedback').html('<div class="alert alert-danger">Connection error! Please try again.</div>'); } }); }); });
第二步:后端邮件处理(以PHP为例)
You'll need a back-end script to handle the form data and send the email. Let's create send-email.php:
基础版(用PHP内置mail()函数)
<?php // 防止直接访问 if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(403); echo json_encode(['success' => false]); exit; } // 获取并过滤表单数据 $name = htmlspecialchars(trim($_POST['name'])); $company = htmlspecialchars(trim($_POST['companyname'])); $email = htmlspecialchars(trim($_POST['email'])); $message = htmlspecialchars(trim($_POST['message'])); // 验证数据 if (empty($name) || empty($company) || empty($email) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { echo json_encode(['success' => false]); exit; } // 设置邮件内容 $to = 'your-email@example.com'; // 替换成你的收件邮箱 $subject = 'New Contact Form Submission from ' . $name; $headers = "From: " . $email . "\r\n"; $headers .= "Reply-To: " . $email . "\r\n"; $headers .= "Content-Type: text/html; charset=UTF-8\r\n"; $email_body = " <html> <head> <title>New Contact Form Submission</title> </head> <body> <h3>Contact Details:</h3> <p><strong>Name:</strong> $name</p> <p><strong>Company:</strong> $company</p> <p><strong>Email:</strong> $email</p> <h3>Message:</h3> <p>$message</p> </body> </html> "; // 发送邮件 if (mail($to, $subject, $email_body, $headers)) { echo json_encode(['success' => true]); } else { echo json_encode(['success' => false]); } ?>
推荐版(用PHPMailer,更可靠)
The built-in mail() function can be unreliable on some servers. PHPMailer is a better choice—here's how to use it:
- Install PHPMailer via Composer:
composer require phpmailer/phpmailer - Update
send-email.phpto use PHPMailer:
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php'; // 如果不用Composer,手动引入PHPMailer文件 if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(403); echo json_encode(['success' => false]); exit; } $name = htmlspecialchars(trim($_POST['name'])); $company = htmlspecialchars(trim($_POST['companyname'])); $email = htmlspecialchars(trim($_POST['email'])); $message = htmlspecialchars(trim($_POST['message'])); if (empty($name) || empty($company) || empty($email) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { echo json_encode(['success' => false]); exit; } $mail = new PHPMailer(true); try { // SMTP配置(根据你的邮箱服务商调整,比如Gmail、Outlook等) $mail->isSMTP(); $mail->Host = 'smtp.example.com'; // 你的SMTP服务器 $mail->SMTPAuth = true; $mail->Username = 'your-email@example.com'; // 你的发件邮箱 $mail->Password = 'your-email-password'; // 邮箱密码或应用专用密码 $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; // 收件人 $mail->setFrom($email, $name); $mail->addAddress('your-email@example.com'); // 你的收件邮箱 // 邮件内容 $mail->isHTML(true); $mail->Subject = 'New Contact Form Submission from ' . $name; $mail->Body = " <html> <head> <title>New Contact Form Submission</title> </head> <body> <h3>Contact Details:</h3> <p><strong>Name:</strong> $name</p> <p><strong>Company:</strong> $company</p> <p><strong>Email:</strong> $email</p> <h3>Message:</h3> <p>$message</p> </body> </html> "; $mail->send(); echo json_encode(['success' => true]); } catch (Exception $e) { echo json_encode(['success' => false, 'error' => $mail->ErrorInfo]); } ?>
第三步:关键注意事项
- Security: Always sanitize user input (like we did with
htmlspecialchars) to prevent XSS attacks. Never trust raw user data. - SMTP Settings: If using PHPMailer, make sure your server allows SMTP connections, and use the correct settings for your email provider (e.g., Gmail uses
smtp.gmail.com, port 587, and requires app-specific passwords if 2FA is enabled). - Testing: Test the form thoroughly—send a few test messages to make sure they land in your inbox (check spam folder too!).
内容的提问来源于stack exchange,提问作者Sikander

