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

如何通过PHP Gmail-SMTP仅发送表单非空字段数据至邮箱?

解决方案

要实现仅显示已填充的字段,你需要先过滤掉空值字段,再动态拼接邮件内容,而非硬编码所有字段。以下是修改后的完整代码:

<?php

//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

if(isset($_POST['insert']))
{
    // 从POST获取所有字段,默认空字符串避免未定义变量警告
    $firstname = $_POST['firstname'] ?? '';
    $lastname = $_POST['lastname'] ?? '';
    $company = $_POST['company'] ?? '';
    $emailaddress = $_POST['emailaddress'] ?? '';
    $phonenumber = $_POST['phonenumber'] ?? '';
    $siteaddress = $_POST['siteaddress'] ?? '';
    $mapreference = $_POST['mapreference'] ?? '';
    $accountno = $_POST['accountno'] ?? '';
    $orderno = $_POST['orderno'] ?? '';
    $dateordered = $_POST['dateordered'] ?? '';
    $daterequired = $_POST['daterequired'] ?? '';
    $deliverypickup = $_POST['deliverypickup'] ?? '';
    $pickuptime = $_POST['pickuptime'] ?? '';
    $passup = $_POST['passup'] ?? '';
    $PLASTER_6000x1350_13mm = $_POST['PLASTER_6000x1350_13mm'] ?? '';
    $PLASTER_6000x1200_13mm = $_POST['PLASTER_6000x1200_13mm'] ?? '';
    $BATTENS_129_6000 = $_POST['BATTENS_129_6000'] ?? '';
    $BATTENS_301_6000 = $_POST['BATTENS_301_6000'] ?? '';
    $BATTENS_308_6000 = $_POST['BATTENS_308_6000'] ?? '';

    //Load Composer's autoloader
    require 'phpmailer/Exception.php';
    require 'phpmailer/SMTP.php';
    require 'phpmailer/PHPMailer.php';

    //Create an instance; passing `true` enables exceptions
    $mail = new PHPMailer(true);

    try {
        //Server settings
        $mail->isSMTP();                                            //Send using SMTP
        $mail->Host       = 'smtp.gmail.com';                       //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->Username   = 'hereIsEmail';                     //SMTP username
        $mail->Password   = '********';                               //SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
        $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

        //Recipients
        $mail->setFrom('hereIsEmail', 'Testing');       //mailer name
        $mail->addAddress('hereIsEmail', 'User');     //Add a recipient

        //Content
        $mail->isHTML(true);                                        //Set email format to HTML
        $mail->Subject = 'ABC';

        // 把字段名和对应变量存入数组,方便遍历维护
        $formFields = [
            'First name' => $firstname,
            'Last name' => $lastname,
            'Company' => $company,
            'Email Address' => $emailaddress,
            'Phone Number' => $phonenumber,
            'Site Address' => $siteaddress,
            'Map Reference' => $mapreference,
            'Account No' => $accountno,
            'Order No' => $orderno,
            'Date Ordered' => $dateordered,
            'Date Required' => $daterequired,
            'Delivery/Pickup' => $deliverypickup,
            'Pickup Time' => $pickuptime,
            'Pass Up' => $passup,
            '10mmPLASTER_6000x1350' => $PLASTER_6000x1350_13mm,
            '13mmPLASTER_6000x1200' => $PLASTER_6000x1200_13mm,
            'BATTENS_129_6000' => $BATTENS_129_6000,
            'BATTENS_301_6000' => $BATTENS_301_6000,
            'BATTENS_308_6000' => $BATTENS_308_6000
        ];

        $emailBody = '';
        // 遍历数组,仅保留非空字段
        foreach($formFields as $label => $value) {
            // 去除首尾空格后判断是否为空,避免仅输入空格的无效字段
            if(trim($value) !== '') {
                $emailBody .= "$label : $value<br>";
            }
        }

        $mail->Body = $emailBody;

        $mail->send();
        echo 'Form Submitted Successfully';
    } catch (Exception $e) {
        echo "Form could not be sent. Mailer Error: {$mail->ErrorInfo}";
    } 
}

关键修改说明

  • 变量初始化:通过$_POST获取字段值并设置默认空字符串,避免PHP抛出未定义变量的警告。
  • 字段数组化:将所有字段名与对应变量存入关联数组,后续新增或修改字段只需调整数组,无需重复修改拼接逻辑。
  • 空字段过滤:遍历数组时,通过trim()去除字段值首尾空格后判断是否为空,仅将有效内容拼接进邮件,确保空字段不会显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:44:53