You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

初学者求助:如何将HTML表单数据发送至邮箱(附表单代码及问题详情)

Fixing 405 Error & Sending Form Emails with PHPMailer + Google SMTP

Hey there! Let's get your contact form up and running smoothly. That 405 error often pops up in local MAMP environments when the PHP script isn't handling POST requests correctly, or the basic mail() function fails (which is super common locally). PHPMailer is the reliable fix here—let's walk through every step clearly.

Step 1: Set Up PHPMailer

First, add PHPMailer to your project. Pick one of these easy options:

  • Option 1 (Composer, recommended if you’re familiar with it): Run composer require phpmailer/phpmailer in your project folder.
  • Option 2 (No Composer): Download the latest PHPMailer zip from its official repo, extract it into a folder named phpmailer in your project root (same directory as your HTML form and form-to-email.php).

Step 2: Rewrite Your form-to-email.php Script

Replace your existing (or empty) form-to-email.php with this commented code—it handles the form data, connects to Google SMTP, and sends the email:

<?php
// Turn on error reporting for debugging (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Import PHPMailer core classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load PHPMailer files (adjust path if you placed the folder elsewhere)
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

// Only accept POST requests (fixes 405 method errors)
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "Method Not Allowed";
    exit;
}

// Sanitize form data to prevent injection issues
$name = htmlspecialchars($_POST['name'] ?? '');
$email = htmlspecialchars($_POST['email'] ?? '');
$socials = htmlspecialchars($_POST['other_socials'] ?? 'No socials provided');
$service = htmlspecialchars($_POST['services'] ?? 'Not selected');
$message = htmlspecialchars($_POST['message'] ?? '');

// Validate required fields (duplicate frontend checks for security)
if (empty($name) || empty($email) || empty($message)) {
    http_response_code(400);
    echo "Please fill all required fields.";
    exit;
}

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

try {
    // Google SMTP Configuration
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com'; // Google's SMTP server
    $mail->SMTPAuth   = true;
    $mail->Username   = 'your-gmail-address@gmail.com'; // Your Gmail address
    $mail->Password   = 'your-app-specific-password'; // Generate this (see Step 3)
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587; // TLS port for Google SMTP

    // Set sender and recipient
    $mail->setFrom($email, $name); // Use the form submitter's email/name
    $mail->addAddress('your-client-email@example.com'); // Client's email to receive submissions

    // Build email content
    $mail->isHTML(true);
    $mail->Subject = "New Contact Form Submission from $name";
    $mail->Body    = "
        <h3>New Enquiry</h3>
        <p><strong>Name:</strong> $name</p>
        <p><strong>Email:</strong> $email</p>
        <p><strong>Socials:</strong> $socials</p>
        <p><strong>Service Requested:</strong> $service</p>
        <p><strong>Message:</strong><br>$message</p>
    ";
    $mail->AltBody = "New Contact Form Submission from $name\n\nName: $name\nEmail: $email\nSocials: $socials\nService: $service\nMessage: $message"; // Plain text fallback for non-HTML inboxes

    // Send the email
    $mail->send();
    echo "Message sent successfully!";
} catch (Exception $e) {
    http_response_code(500);
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>

Step 3: Generate Google App-Specific Password

Google blocks regular password access for SMTP now—you need an app-specific password to connect:

  1. Go to your Google Account > Security
  2. Enable 2-Step Verification (this is required to create app passwords)
  3. Under "Signing in to Google", select App Passwords
  4. Choose "Mail" as the app, "Other (custom name)" as the device, then click "Generate"
  5. Copy the 16-character password that appears, and paste it into the $mail->Password line in your PHP script.

Step 4: Fix the 405 Error & Test

  • Double-check that your form-to-email.php is in the right location relative to your HTML form. If it’s in a subfolder, update the form’s action attribute (e.g., action="./php/form-to-email.php").
  • Make sure MAMP is running, and your project files are in MAMP’s htdocs folder.
  • Open your HTML form in a browser, fill in the fields, and hit "Send message". You’ll see a success message if it works, and the client’s email should receive the submission.

Quick Check for Your Existing Form

Your HTML form is already set up well—just confirm:

  • The method="POST" attribute is correctly set (it is in your code)
  • All required fields have required="required" (you’ve got this covered)
  • The name attributes match what we’re using in the PHP script (e.g., name="name" maps to $_POST['name']—yours are all correct!)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:12:36