PHP Mail() Function with headers

2019-07-07 01:12发布

问题:

I always struggle when using headers along with the PHP mail() function. The problem is always the same, last year, this time, as long as I remember, it drives me mad.

The problem is that the headers are simply displayed in the email message.

Example received mail :

http://nl.tinypic.com/view.php?pic=63va5z&s=8#.U8PmeED8rbw

Source :

$onderwerp = "Bedankt voor uw bestelling met order nummer # ".$row['id'];
$ontvanger = "customer@customer.be";
$reply = "reply@reply.be";
//$reply = htmlspecialchars($_POST['je_email']); 

$headers = "Content-type: text/html; charset=iso-8859-1\r\n"; 
$headers .= "MIME-Version: 1.0\r\n";    

$headers .= "Reply-To: Webmaster < reply@website.be >\r\n"; // reply-adres
//$headers .= "Cc:  webmaster@website.be , crewlid@website.be \r\n"; //copy
//$headers .= "Bcc:  crew@website.be \r\n"; // blind copy
$headers .= "From: TEST SOME NAME | GW8 <$reply>\r\n"; // de afzender van de mail
$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
$headers .= "X-Priority: 1\r\n"; // 3 voor onbelangrijk 
$headers .= "Priority: Urgent\r\n";
$headers .= "Importance: High\r\n"; // Low voor onbelangrijk
$headers .= "X-MSMail-Priority: High\r\n"; // Low voor onbelangrijk  

$bericht = "<strong>TEST</strong>"; 

mail($ontvanger,$onderwerp,$bericht,$headers);

Which snippet I use, always the same problem.. Headers displayed in email content, as shown in screenshot.

Does anybody know how I can fix this ? I have a strong feeling this is a server-side problem..

回答1:

It would be better to use established mailing solutions instead of PHPs mail() function if you're not experienced with that.

A few hints:

Readability and preventing errors

For readability and programming purposes - think about implementing the headers as array. Instead of adding \r\n in every line you could work like that. When building together the mail in the mail() function you can implode() it.

// Building headers.
$headers = array();
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859';
$headers[] = 'X-Mailer: PHP/'. phpversion();
// ...

// Sending mail.
mail($ontvanger, $onderwerp, $bericht, implode(PHP_EOL, $headers));

Sending HTML mails

I recommend to send the mails as multipart MIME messages when sending html. This differs from your approch. Because it's not that easy to explain in a message. Maybe try it with that link: http://webcheatsheet.com/php/send_email_text_html_attachment.php

I've used multipart mime messages for example to send HTML mails with custom attachments via PHP.

There is no necessarity of paying attention to the order of the different headers. But it's some sort of a good practice to group them and start with the most important ones.