You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过PHP实现包含日期选择器的表单数据HTML邮件发送

Got it, let's walk through exactly how to build this—from the frontend form with a date picker to the PHP backend that sends an HTML email with all the form data. I'll include code examples and best practices so you can implement this smoothly.

1. Build the Frontend Form with Date Picker

First, create an HTML form that includes your input fields and a native date picker (most modern browsers support this natively, no extra libraries needed). We'll add basic client-side validation to ensure users fill in required fields.

<form action="send-email.php" method="POST" id="submissionForm">
  <div class="form-group">
    <label for="fullName">Full Name:</label>
    <input type="text" id="fullName" name="fullName" required>
  </div>
  <div class="form-group">
    <label for="contactEmail">Your Email:</label>
    <input type="email" id="contactEmail" name="contactEmail" required>
  </div>
  <div class="form-group">
    <label for="bookingDate">Booking Date:</label>
    <input type="date" id="bookingDate" name="bookingDate" required>
  </div>
  <div class="form-group">
    <label for="serviceType">Service Type:</label>
    <select id="serviceType" name="serviceType" required>
      <option value="">Select a service</option>
      <option value="consultation">Consultation</option>
      <option value="workshop">Workshop</option>
      <option value="support">Technical Support</option>
    </select>
  </div>
  <div class="form-group">
    <label for="additionalNotes">Additional Notes:</label>
    <textarea id="additionalNotes" name="additionalNotes" rows="4"></textarea>
  </div>
  <button type="submit">Submit Request</button>
</form>

The type="date" input will render a browser-specific date picker, and it submits the date in YYYY-MM-DD format—easy for PHP to handle.

2. PHP Backend: Handle Submission & Send HTML Email

Next, create the send-email.php file to process the form data, validate it, and send the HTML email. I'll cover two approaches: the native mail() function (simple but server-dependent) and PHPMailer (more reliable for most use cases).

2.1 Basic Implementation with Native mail()

This works if your web server has sendmail configured correctly (most shared hosting does, but local servers like XAMPP may need setup).

<?php
// Only process POST requests
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: index.html");
    exit;
}

// Sanitize and retrieve form data
$fullName = htmlspecialchars(trim($_POST['fullName']));
$contactEmail = filter_var(trim($_POST['contactEmail']), FILTER_SANITIZE_EMAIL);
$bookingDate = htmlspecialchars(trim($_POST['bookingDate']));
$serviceType = htmlspecialchars(trim($_POST['serviceType']));
$additionalNotes = htmlspecialchars(trim($_POST['additionalNotes']));

// Validate required fields
if (empty($fullName) || empty($contactEmail) || empty($bookingDate) || empty($serviceType)) {
    echo "Please fill in all required fields.";
    exit;
}

// Validate email format
if (!filter_var($contactEmail, FILTER_VALIDATE_EMAIL)) {
    echo "Please enter a valid email address.";
    exit;
}

// Email configuration
$to = "your-target-email@example.com"; // Replace with your email
$subject = "New Service Request from $fullName";

// Set headers for HTML email
$headers = "From: $contactEmail\r\n";
$headers .= "Reply-To: $contactEmail\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n"; // Critical for HTML rendering

// Build HTML email content
$htmlContent = "
<html>
<head>
    <title>New Service Request</title>
    <style>
        .email-wrapper { max-width: 600px; margin: 20px auto; font-family: Arial, sans-serif; border: 1px solid #eee; padding: 20px; }
        .field-group { margin-bottom: 15px; }
        .field-label { font-weight: bold; display: block; margin-bottom: 5px; color: #333; }
        .field-value { padding: 8px; background: #f8f8f8; border-radius: 4px; }
    </style>
</head>
<body>
    <div class='email-wrapper'>
        <h2>New Service Request Received</h2>
        <div class='field-group'>
            <span class='field-label'>Name:</span>
            <div class='field-value'>$fullName</div>
        </div>
        <div class='field-group'>
            <span class='field-label'>Email:</span>
            <div class='field-value'>$contactEmail</div>
        </div>
        <div class='field-group'>
            <span class='field-label'>Booking Date:</span>
            <div class='field-value'>$bookingDate</div>
        </div>
        <div class='field-group'>
            <span class='field-label'>Service Type:</span>
            <div class='field-value'>$serviceType</div>
        </div>
        <div class='field-group'>
            <span class='field-label'>Additional Notes:</span>
            <div class='field-value'>" . ($additionalNotes ?: "None") . "</div>
        </div>
    </div>
</body>
</html>
";

// Send the email
if (mail($to, $subject, $htmlContent, $headers)) {
    echo "Thank you! Your request has been submitted successfully.";
} else {
    echo "Oops! Something went wrong. Please try again later.";
}
?>

Key Notes for Native mail():

  • We use htmlspecialchars() to sanitize input and prevent XSS attacks (critical since we're sending HTML).
  • The Content-Type header ensures the email client renders the HTML instead of showing raw code.

The native mail() function relies on server sendmail config, which can be flaky. PHPMailer handles SMTP authentication, avoids delivery issues, and supports features like attachments.

  1. Install PHPMailer via Composer:

    composer require phpmailer/phpmailer
    
  2. PHPMailer Implementation:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Path to Composer's autoload file

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: index.html");
    exit;
}

// Sanitize and validate data (same as before)
$fullName = htmlspecialchars(trim($_POST['fullName']));
$contactEmail = filter_var(trim($_POST['contactEmail']), FILTER_SANITIZE_EMAIL);
$bookingDate = htmlspecialchars(trim($_POST['bookingDate']));
$serviceType = htmlspecialchars(trim($_POST['serviceType']));
$additionalNotes = htmlspecialchars(trim($_POST['additionalNotes']));

if (empty($fullName) || empty($contactEmail) || empty($bookingDate) || empty($serviceType)) {
    echo "Please fill in all required fields.";
    exit;
}

if (!filter_var($contactEmail, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format.";
    exit;
}

// Initialize PHPMailer
$mail = new PHPMailer(true);

try {
    // SMTP Server Settings (adjust for your email provider)
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com'; // e.g., smtp.gmail.com for Gmail
    $mail->SMTPAuth = true;
    $mail->Username = 'your-email@example.com'; // Your email address
    $mail->Password = 'your-app-password-or-email-password'; // Use app password for Gmail (with 2FA enabled)
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port = 465; // Use 587 if using STARTTLS encryption

    // Recipients
    $mail->setFrom($contactEmail, $fullName);
    $mail->addAddress('your-target-email@example.com'); // Your target email
    $mail->addReplyTo($contactEmail, $fullName);

    // Email Content
    $mail->isHTML(true);
    $mail->Subject = "New Service Request from $fullName";
    $mail->Body = "
    <html>
    <head>
        <title>New Service Request</title>
        <style>
            .email-wrapper { max-width: 600px; margin: 20px auto; font-family: Arial, sans-serif; border: 1px solid #eee; padding: 20px; }
            .field-group { margin-bottom: 15px; }
            .field-label { font-weight: bold; display: block; margin-bottom: 5px; color: #333; }
            .field-value { padding: 8px; background: #f8f8f8; border-radius: 4px; }
        </style>
    </head>
    <body>
        <div class='email-wrapper'>
            <h2>New Service Request Received</h2>
            <div class='field-group'>
                <span class='field-label'>Name:</span>
                <div class='field-value'>$fullName</div>
            </div>
            <div class='field-group'>
                <span class='field-label'>Email:</span>
                <div class='field-value'>$contactEmail</div>
            </div>
            <div class='field-group'>
                <span class='field-label'>Booking Date:</span>
                <div class='field-value'>$bookingDate</div>
            </div>
            <div class='field-group'>
                <span class='field-label'>Service Type:</span>
                <div class='field-value'>$serviceType</div>
            </div>
            <div class='field-group'>
                <span class='field-label'>Additional Notes:</span>
                <div class='field-value'>" . ($additionalNotes ?: "None") . "</div>
            </div>
        </div>
    </body>
    </html>";
    $mail->AltBody = "Name: $fullName\nEmail: $contactEmail\nBooking Date: $bookingDate\nService Type: $serviceType\nAdditional Notes: " . ($additionalNotes ?: "None"); // Plain text fallback

    $mail->send();
    echo "Thank you! Your request has been submitted successfully.";
} catch (Exception $e) {
    echo "Oops! Something went wrong. Error: {$mail->ErrorInfo}";
}
?>

PHPMailer Tips:

  • For Gmail, enable 2FA and use an App Password instead of your regular password.
  • Adjust SMTP settings for your provider (Outlook uses smtp.office365.com, port 587 with STARTTLS).
3. Best Practices to Keep in Mind
  • Sanitize All Input: Never trust raw $_POST data—use htmlspecialchars() and filter_var() to prevent XSS and email injection.
  • CSRF Protection: Add a CSRF token to your form to block cross-site request forgery:
    // In your form page (start session first with session_start())
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    
    <!-- Add hidden field to form -->
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    
    // In send-email.php
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo "Invalid request.";
        exit;
    }
    
  • Date Formatting: To display the date in a friendlier format (e.g., "January 1, 2024"), use PHP's date() function:
    $formattedDate = date("F j, Y", strtotime($bookingDate));
    
  • Testing: Always test the form thoroughly—check if emails are delivered, date values are correct, and validation works as expected.

内容的提问来源于stack exchange,提问作者Gomathi Govindharaj

火山引擎 最新活动