I am using following script to send email through PHP. However, I am getting error "PHP Warning: mail(): Found numeric header (4) in /home/....public_html/.../sendemail.php on line 16"
Any help please.
PHP Script
<?php $name = @trim(stripslashes($_POST['name'])); $from = @trim(stripslashes($_POST['email'])); $subject = @trim(stripslashes($_POST['subject'])); $message = @trim(stripslashes($_POST['message'])); $to = 'xxxxx@xmail.com'; $headers = array(); $headers[] = "MIME-Version: 1.0"; $headers[] = "Content-type: text/plain; charset=UTF-8"; $headers[] = "From: {$name} <{$from}>"; $headers[] = "Reply-To: <{$from}>"; $headers[] = "Subject: {$subject}"; $headers[] = "X-Mailer: PHP/".phpversion(); mail($to, $subject, $message, $headers); die;
Advertisement
Answer
If you wanna pass the headers as array, then you need to specify the header names as array keys! (PHP documentation: “If an array is passed, its keys are the header names and its values are the respective header values.”).
There are now 2 solutions.
Solution 1 (Header as string):
$headers = "MIME-Version: 1.0"; $headers .= "Content-type: text/plain; charset=UTF-8"; $headers .= "From: {$name} <{$from}>"; $headers .= "Reply-To: <{$from}>"; $headers .= "Subject: {$subject}"; $headers .= "X-Mailer: PHP/".phpversion();
Solution 2 (Headers as array):
$headers = [ 'MIME-Version' => 'MIME-Version: 1.0', 'Content-type' => 'text/plain; charset=UTF-8', 'From' => "{$name} <{$from}>", 'Reply-To' => $from, 'Subject' => $subject, 'X-Mailer' => 'PHP/' . phpversion(), ];
To check if mail()
works you can check for the last error.
Example:
$success = mail('example@example.com', 'My Subject', $message); if (!$success) { $errorMessage = error_get_last()['message']; }
And btw. to avoid any problems with the receiving email servers because of non conform RFC, you should use a mailer class like SwiftMailer or PHPMailer.