boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

使用 PHP 发送包含表单答案的电子邮件


avatar
站长 2025年8月17日 3

使用 PHP 发送包含表单答案的电子邮件

本文档旨在指导开发者使用 PHP 处理 HTML 表单提交的数据,并将其通过电子邮件发送出去。我们将详细讲解如何配置表单的 action 属性,以及如何使用 PHP 代码接收、处理表单数据,并最终发送邮件。同时,也会介绍使用像 PHPMailer 这样的库来更安全、更便捷地发送邮件。

HTML 表单配置

首先,确保你的 HTML 表单正确配置了 action 属性。action 属性指定了表单数据提交后,由哪个 URL 来处理这些数据。如果服务器返回 404 错误,很可能是因为 action 属性指向的 PHP 文件路径不正确。

一种常见的错误是缺少起始斜杠 /。如果 mail.php 文件位于网站根目录下,应该将 action 属性设置为 /mail.php。

<form action="/mail.php" method="post">   <div class="large-7 columns">     <div id="contact-form">       <div id="name">         <div class="form-icon">           <i class="typcn typcn-user"></i>         </div>         <input name="name" id="form-name" type="text" placeholder="Name" />       </div>        <div id="email">         <div class="form-icon">           <i class="typcn typcn-mail"></i>         </div>         <input           name="email"           id="form-email"           type="text"           placeholder="Email"         />       </div>        <div id="message">         <div class="form-icon">           <i class="typcn typcn-pencil"></i>         </div>         <textarea           name="message"           id="form-message"           placeholder="Message"         ></textarea>       </div>       <input class="btn" type="submit" name="submit" value="Submit" />     </div>   </div> </form>

确保 method 属性设置为 post,因为我们要在 PHP 中使用 $_POST 超全局变量来访问表单数据。

立即学习PHP免费学习笔记(深入)”;

PHP 处理表单数据并发送邮件

以下是一个简单的 mail.php 示例,用于接收表单数据并发送电子邮件:

<?php   if (isset($_POST['submit'])) {     $name = $_POST['name'];     $email = $_POST['email'];     $message = $_POST['message'];     $formcontent="From: $name nMessage: $message";     $recipient = "your_email@example.com"; // 替换为你的邮箱地址     $subject = "Contact Form";     $mailheader = "From: $email rn";     mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");     echo "Thank You!" . " -" . "<a href='index.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";   } ?>

代码解释:

  1. isset($_POST[‘submit’]): 检查是否通过 POST 方法提交了名为 submit 的表单字段。
  2. $name = $_POST[‘name’];, $email = $_POST[’email’];, $message = $_POST[‘message’];: 从 $_POST 数组中获取表单字段的值,并将其分配给相应的变量。
  3. $formcontent=”From: $name nMessage: $message”;: 将表单数据格式化为邮件正文。
  4. $recipient = “your_email@example.com”;: 指定收件人的电子邮件地址。 务必替换为你自己的邮箱地址。
  5. $subject = “Contact Form”;: 设置邮件主题。
  6. $mailheader = “From: $email rn”;: 设置邮件头,指定发件人的电子邮件地址。
  7. mail($recipient, $subject, $formcontent, $mailheader) or die(“Error!”);: 使用 PHP 的 mail() 函数发送电子邮件。如果发送失败,则输出 “Error!”。
  8. echo “Thank You!” . ” -” . “ Return Home“;: 发送成功后,向用户显示一条感谢消息,并提供返回主页的链接。

注意事项:

  • mail() 函数的安全性较低,容易被滥用发送垃圾邮件。
  • mail() 函数在某些服务器配置下可能无法正常工作。
  • 直接使用用户提交的电子邮件地址作为邮件头中的 “From” 字段是不安全的,容易被利用进行邮件欺骗。

使用 PHPMailer 库发送邮件 (推荐)

为了更安全、更可靠地发送电子邮件,强烈建议使用 PHPMailer 这样的库。PHPMailer 提供了丰富的功能,包括:

  • 支持 SMTP 认证,可以避免被当作垃圾邮件。
  • 支持 HTML 邮件格式。
  • 支持附件。
  • 易于使用。

安装 PHPMailer:

你可以通过 Composer 安装 PHPMailer:

composer require phpmailer/phpmailer

使用 PHPMailer 的示例代码:

<?php use PHPMailerPHPMailerPHPMailer; use PHPMailerPHPMailerException;  require 'vendor/autoload.php'; // 引入 Composer 自动加载器  if (isset($_POST['submit'])) {     $name = $_POST['name'];     $email = $_POST['email'];     $message = $_POST['message'];      $mail = new PHPMailer(true);      try {         //Server settings         $mail->SMTPDebug = 0;                      // Enable verbose debug output (0 for no debug output)         $mail->isSMTP();                                            // Send using SMTP         $mail->Host       = 'smtp.example.com';                    // Set the SMTP server to send through         $mail->SMTPAuth   = true;                                   // Enable SMTP authentication         $mail->Username   = 'your_email@example.com';                     // SMTP username         $mail->Password   = 'your_password';                               // SMTP password         $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged         $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above          //Recipients         $mail->setFrom('your_email@example.com', 'Your Name'); // 替换为你的邮箱和名称         $mail->addAddress('recipient@example.com', 'Recipient Name');     // Add a recipient (替换为收件人的邮箱和名称)         $mail->addReplyTo($email, $name); //回复邮件地址设置为用户的邮箱          // Content         $mail->isHTML(false);                                  // Set email format to HTML (设置为 false 发送纯文本邮件)         $mail->Subject = 'Contact Form';         $mail->Body    = "From: $name nEmail: $email nMessage: $message";         // $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; //纯文本备用正文          $mail->send();         echo 'Message has been sent';     } catch (Exception $e) {         echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";     }      echo "Thank You!" . " -" . "<a href='index.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>"; } ?>

代码解释:

  1. 引入 PHPMailer 类。
  2. 实例化 PHPMailer 对象。
  3. 配置 SMTP 服务器的地址、端口、用户名、密码等信息。 务必替换为你自己的 SMTP 服务器信息。
  4. 设置发件人、收件人、邮件主题和正文。
  5. 调用 send() 方法发送邮件。
  6. 使用 try-catch 块捕获异常,以便在发送失败时显示错误信息。

重要提示:

  • 你需要一个有效的 SMTP 服务器才能使用 PHPMailer 发送邮件。
  • 请勿将密码等敏感信息直接硬编码到代码中。建议使用环境变量或其他安全的方式来存储这些信息。
  • 确保你的服务器已启用 openssl 扩展,PHPMailer 才能使用 TLS 加密。

总结

使用 PHP 发送电子邮件需要谨慎处理安全性问题。建议使用 PHPMailer 这样的库,并配置 SMTP 认证,以避免被当作垃圾邮件。同时,要避免直接使用用户提交的电子邮件地址作为邮件头中的 “From” 字段,以防止邮件欺骗。正确配置 HTML 表单的 action 属性,确保服务器能够正确找到并执行 PHP 脚本。



评论(已关闭)

评论已关闭