PHP发送邮件报错:Header必须为数组问题求助
Hey there! Let's tackle that frustrating error you're seeing. The core issue here is how you're passing email headers to the PEAR Mail class—this library expects headers to be an associative array, not a plain text string (which is what many older mail scripts use).
Why the Error Happens
PEAR's Mail::send() method requires the headers parameter to be a structured array where keys are header names (like From, To, Subject) and values are their corresponding content. If you're passing a string with line breaks (e.g., "From: support@example.com\r\nSubject: ..."), the class will throw that "Header must be an array" error.
Corrected Code Example
Here's how to adjust your script to fix the issue, with comments explaining the key changes:
<?php ini_set("include_path", '/home/ny1zdip8aag5/php:' . ini_get("include_path") ); include('Mail.php'); if (isset($_POST['submit'])) { // Collect form data (your existing code) $name = $_POST['name']; $email = $_POST['email']; $mobile = $_POST['mobile']; $address = $_POST['address']; $pan = $_POST['pan']; $aadhar = $_POST['aadhar']; $comp = $_POST['comp']; $amount = $_POST['amount']; $loss = $_POST['loss']; $message = $_POST['message']; // Configure sender and recipient emails $email_from = 'support@yourdomain.com'; // Fill in your valid sender email $email_to = 'your-recipient@example.com'; // Fill in where you want to receive submissions // Build the plain-text email body $body = "You've received a new form submission:\n\n" . "Name: $name\n" . "Email: $email\n" . "Mobile: $mobile\n" . "Address: $address\n" . "PAN: $pan\n" . "Aadhar: $aadhar\n" . "Company: $comp\n" . "Amount: $amount\n" . "Loss: $loss\n" . "Message: $message"; // 🔑 Critical Fix: Use an array for headers instead of a string $headers = array( 'From' => $email_from, 'To' => $email_to, 'Subject' => 'New Form Submission', 'Reply-To' => $email // Lets replies go directly to the user's email ); // Initialize the Mail object (use 'smtp' instead of 'mail' if you need SMTP auth) $mail = Mail::factory('mail'); // Send the email $result = $mail->send($email_to, $headers, $body); // Handle success/error if (PEAR::isError($result)) { echo "PHP send mail error : " . $result->getMessage(); } else { echo "Form submission sent successfully!"; } } ?>
Additional Tips
- If you need to use SMTP (recommended for better deliverability), replace the
Mail::factory('mail')line with something like this (adjust the parameters to match your SMTP provider):$smtp_config = array( 'host' => 'smtp.yourdomain.com', 'port' => 587, 'auth' => true, 'username' => 'your-smtp-username', 'password' => 'your-smtp-password' ); $mail = Mail::factory('smtp', $smtp_config); - Always validate and sanitize user input before using it in emails to avoid header injection attacks (e.g., use
filter_var($email, FILTER_VALIDATE_EMAIL)to check the user's email is valid).
内容的提问来源于stack exchange,提问作者Rajiv Sharma

