HTML网站联系表单邮件发送问题:PHP失效求替代方案或免费API
Hey there! Let's tackle this email sending issue step by step. First, let's unpack why your PHP mail() function showed success but no emails landed in your inbox—then we'll cover reliable alternatives and free APIs.
先修复你的PHP方案:换掉原生mail()函数
The native PHP mail() function is super low-level and relies on your server having a properly configured Mail Transfer Agent (MTA) running. Most shared hosts don't enable this by default, or the emails get flagged as spam before reaching your inbox. A way better option is to use PHPMailer, which supports SMTP (authenticated email sending) and is way more reliable.
Here's a revised version of your code using PHPMailer:
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // Load PHPMailer files (adjust the path to match your setup) require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; if(isset($_POST['email'])) { $email_to = "you@yourdomain.com"; $email_subject = "New Contact Form Submission"; // Error handling function function died($error) { echo "We're sorry, but there were errors with your submission.<br><br>"; echo $error."<br><br>"; echo "Please go back and fix these issues.<br><br>"; die(); } // Validate required form fields exist if(!isset($_POST['first_name']) || !isset($_POST['last_name']) || !isset($_POST['email']) || !isset($_POST['comments'])) { died('It looks like some required fields are missing from your submission.'); } // Sanitize form inputs $first_name = trim($_POST['first_name']); $last_name = trim($_POST['last_name']); $email_from = trim($_POST['email']); $telephone = trim($_POST['telephone']); $comments = trim($_POST['comments']); $error_message = ""; // Validate email format $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/'; if(!preg_match($email_exp, $email_from)) { $error_message .= 'The email address you entered doesn\'t look valid.<br>'; } // Validate name formats $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp, $first_name)) { $error_message .= 'Your first name contains invalid characters.<br>'; } if(!preg_match($string_exp, $last_name)) { $error_message .= 'Your last name contains invalid characters.<br>'; } if(strlen($comments) < 2) { $error_message .= 'Your comments are too short.<br>'; } if(strlen($error_message) > 0) { died($error_message); } // Build email content $email_content = "Contact Form Submission:\n\n"; $email_content .= "First Name: {$first_name}\n"; $email_content .= "Last Name: {$last_name}\n"; $email_content .= "Email: {$email_from}\n"; $email_content .= "Telephone: {$telephone}\n"; $email_content .= "Comments: {$comments}\n"; // Initialize PHPMailer $mail = new PHPMailer(true); try { // Configure SMTP (use your email provider's SMTP details, e.g., Gmail, Outlook, or your host's SMTP) $mail->isSMTP(); $mail->Host = 'smtp.yourdomain.com'; // Example: smtp.gmail.com $mail->SMTPAuth = true; $mail->Username = 'your-email@yourdomain.com'; // Your sender email $mail->Password = 'your-app-password-or-email-password'; // Use app-specific password if using Gmail $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; // Set sender and recipient $mail->setFrom($email_from, "{$first_name} {$last_name}"); $mail->addAddress($email_to); $mail->addReplyTo($email_from); // Set email content $mail->isHTML(false); $mail->Subject = $email_subject; $mail->Body = $email_content; $mail->send(); echo 'Thank you for reaching out! We\'ll get back to you soon.'; } catch (Exception $e) { echo "Oops! We couldn't send your message right now. Error: {$mail->ErrorInfo}"; } } ?>
This setup uses authenticated SMTP, so your emails are way less likely to get marked as spam, and you'll get clear error messages if something goes wrong.
替代PHP的方案:免费邮件发送工具与API
If you don't want to maintain a PHP backend, here are some great free options:
Formspree (perfect for static sites)
No backend code needed! Sign up for a free account, get a form endpoint, and point your HTML form'sactionto it:<form action="https://formspree.io/f/YOUR_UNIQUE_FORM_ID" method="POST"> <input type="text" name="first_name" required placeholder="First Name"> <input type="text" name="last_name" required placeholder="Last Name"> <input type="email" name="email" required placeholder="Your Email"> <input type="tel" name="telephone" placeholder="Telephone"> <textarea name="comments" required placeholder="Your Comments"></textarea> <button type="submit">Send Message</button> </form>The free tier lets you receive 50 submissions per month, which is enough for most small sites.
SendGrid Free Tier
Send up to 100 emails per month for free. You'll need a simple backend proxy (to keep your API key secure—never expose it in frontend code!) using tools like Vercel Functions or Netlify Functions. Here's a quick Node.js example:exports.handler = async (event) => { const sgMail = require('@sendgrid/mail'); sgMail.setApiKey('YOUR_SENDGRID_API_KEY'); const { first_name, last_name, email, telephone, comments } = JSON.parse(event.body); const msg = { to: 'you@yourdomain.com', from: email, subject: 'New Contact Form Submission', text: `First Name: ${first_name}\nLast Name: ${last_name}\nEmail: ${email}\nTelephone: ${telephone}\nComments: ${comments}` }; try { await sgMail.send(msg); return { statusCode: 200, body: JSON.stringify({ message: 'Success' }) }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: error.message }) }; } };Mailgun Free Tier
Offers 5,000 free emails per month (for US-based accounts). Similar to SendGrid, you'll need a backend proxy to call their API securely.
Quick note: Why HTML can't send emails directly
HTML is just a markup language—it doesn't have the ability to communicate with email servers. Sending emails requires connecting to an SMTP server, which needs to be done via backend code or a third-party service (for security and anti-spam reasons, browsers block frontend code from accessing email servers directly).
内容的提问来源于stack exchange,提问作者shami sheikh

