php – wp_mail vs mail functions and header arrays


I’ve been having issues using wp_mail and mail functions in an application when specifying header elements in the function.

I usually set up the header as an array, as in

$mailheader = array(
                'MIME-Version' => '1.0',
                'Content-type' => ' text/html; charset=utf-8',
                'From' => ''  ,

Using the mail() command, the headers are processed correctly, and the message is sent as an HTML mail.

mail("", "my subject", "<p>A message here.</p>", $mailheader);

But if I use the same command with the wp_mail function (on a WP 6.x site), the message is sent as plain text:

wp_mail("", "my subject", "<p>A message here.</p>", $mailheader);

If you want to use an array for the headers in wp_mail, you have to convert it text:

        foreach ($mailheader as $key => $value) {

            $header_wp .= "$key: $value \r\n";   // for wp-mail header which doesn't do arrays

(Note the use of double quotes in the statement, so the \r\n is processed properly.)

And then use this wp_mail command:

wp_mail("", "my subject", "<p>A message here.</p>", $header_wp );

This will result in an HTML-formatted message when using wp_mail.

I have verified this on different WP 6.01 sites with PHP versions 7.3 and 8.x. The processing of the header by wp_mail happens before it is sent to phpMailer.

I spent a couple of weeks fighting this one, so wanted to alert others.

I’ll put the correct code in my answer to the question.

Rick Hellewell 4 months 2022-08-05T17:52:18-05:00 0 Answers 0 views 0

Leave an answer