如何用PHPMailer发送下拉选择框的值到邮件?求助
使用PHPMailer发送下拉选择框的值到邮箱
先修正前端代码的问题
你的前端JS存在变量名错误,且单选下拉框不需要数组命名,修正后的index.php代码如下:
<form id="myForm"> <label>Country</label> <select id="country" name="country" class="select"> <option value="">-Select-</option> <option value="United States">United States</option> <option value="Canada">Canada</option> </select> <button type="button" onclick="sendEmail()" value="Send An Email">Submit</button> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> function sendEmail() { var countrySelect = $('#country'); if (isNotEmpty(countrySelect)) { $.ajax({ url: 'sendEmail.php', method: 'POST', data: { country: countrySelect.val() }, success: function (response) { if (response.success) { window.location = "success.html"; } else { alert('邮件发送失败,请稍后重试'); } }, error: function() { alert('请求出错'); } }); } } function isNotEmpty(caller) { if (caller.val() === "") { caller.css('border', '1px solid red'); return false; } else { caller.css('border', ''); return true; } } </script>
修正点:
- 下拉框
name从country[]改为country(单选场景无需数组) - 统一JS变量名为
countrySelect,避免未定义错误 - 完善AJAX的错误处理逻辑,增加返回状态判断
配置PHPMailer发送邮件
首先确保已安装PHPMailer:
- Composer安装:执行
composer require phpmailer/phpmailer - 手动安装:下载PHPMailer源码后,将
src目录放到项目中
完整的sendEmail.php代码:
<?php // 引入PHPMailer类 use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // Composer安装引入自动加载 require 'vendor/autoload.php'; // 手动安装则引入对应文件 // require 'PHPMailer/src/Exception.php'; // require 'PHPMailer/src/PHPMailer.php'; // require 'PHPMailer/src/SMTP.php'; // 获取前端传入的国家值 $country = $_POST['country'] ?? ''; // 参数验证 if (empty($country)) { echo json_encode(['success' => false, 'msg' => '请选择国家']); exit; } // 初始化PHPMailer $mail = new PHPMailer(true); try { // SMTP服务器配置 $mail->SMTPDebug = 0; // 生产环境设为0关闭调试,调试时设为2 $mail->isSMTP(); $mail->Host = 'smtp.example.com'; // 替换为你的邮箱SMTP地址(如smtp.qq.com) $mail->SMTPAuth = true; $mail->Username = 'your-email@example.com'; // 你的邮箱账号 $mail->Password = 'your-auth-code'; // 邮箱SMTP授权码(非登录密码) $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // 加密方式:SMTPS或TLS $mail->Port = 465; // 对应端口:465(SMTPS)/587(TLS) // 收件人配置 $mail->setFrom('your-email@example.com', '发送者名称'); $mail->addAddress('recipient@example.com', '收件人名称'); // 邮件内容 $mail->isHTML(true); $mail->Subject = '用户选择的国家信息'; $mail->Body = "用户选择的国家是:<strong>{$country}</strong>"; $mail->AltBody = "用户选择的国家是:{$country}"; // 纯文本备用内容 $mail->send(); echo json_encode(['success' => true, 'msg' => '邮件发送成功']); } catch (Exception $e) { echo json_encode(['success' => false, 'msg' => "邮件发送失败:{$mail->ErrorInfo}"]); } ?>
配置说明:
- 替换
Host、Username、Password为你的邮箱SMTP信息,授权码需在邮箱后台开启POP3/SMTP服务后获取 - 根据邮箱服务商调整
SMTPSecure和Port,比如QQ邮箱用SMTPS+465,Gmail用TLS+587
注意事项
- 确保服务器开启PHP的curl扩展(PHPMailer依赖)
- 测试阶段可开启
SMTPDebug=2查看发送日志排查问题
内容的提问来源于stack exchange,提问作者Bill
相关产品推荐
相关产品推荐

