John Davidson

php - PHP8 mail function adding space prefixes to headers

0 comments
Message:


I just upgraded from PHP 7.4 to 8.0. All of the sudden outgoing mails are getting spaces prefixed to the custom headers.


Here's the code:


$headers = [
'From: Somebody <[email protected]>',
'Content-Type: text/html; charset="UTF-8"',
];
mail('[email protected]', 'Subject', 'Body', implode("\n", $headers));

A message that came in before the upgrade looked like this:


To: [email protected]
Subject: Subject
From: Somebody <[email protected]>
Content-Type: text/html; charset="UTF-8"
Message-Id: <E1n1vlx-0002C5-FC@hostname>

Body goes here

After the upgrade, the same code sends a message which looks like this for the receiver:


From: [email protected]
X-Google-Original-From: Somebody <[email protected]>
Content-Type: text/html; charset="UTF-8"
To: [email protected]
Subject: Subject
Message-Id: <E1n20bv-0007st-Eh@hostnme>

Body goes here

The Content-Type header is getting a space added to the beginning and thus mail clients are ignoring it. exim4 doesn't have any logs of the full outgoing message so I'm not sure where to turn next.



My Answer:
', 'Reply-To: reply@example.com', 'X-Mailer: PHP/' . phpversion()];$subject = 'Test Email';$message = 'This is a test email.';mail('recipient@example.com', $subject, $message, implode("\r\n", $headers));?>

After upgrading to PHP 8.0, you may need to make some changes to your code to ensure that the headers are formatted correctly. One possible solution is to trim each header before adding it to the $headers array. This will remove any leading or trailing spaces that may be causing the issue.

Here's an updated version of your code with the headers trimmed:

$headers = [ 'From: Somebody ', 'Reply-To: reply@example.com', 'X-Mailer: PHP/' . phpversion()];$headers = array_map('trim', $headers);$subject = 'Test Email';$message = 'This is a test email.';mail('recipient@example.com', $subject, $message, implode("\r\n", $headers));

By using the array_map function with the trim function, you can ensure that any leading or trailing spaces are removed from each header before sending the email. This should help prevent any additional spaces from being added to the headers in PHP 8.0.

Rate this post

3 of 5 based on 5590 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us