0

I'm sending mails using the PHP mail() function. The mail headers is not working properly.

$charset = mb_detect_encoding($message);

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: '.$from . "\r\n";    
$headers .= 'Content-type: text/html; charset='.$charset  . "\r\n"; 
$headers .= 'Reply-To: '.$from . "\r\n";
$headers .= 'X-Mailer: php';

In the above code, the only first line is parsed and the later 4 lines are showing in the message body. "From" was not set.

$charset = mb_detect_encoding($message);

$headers  = 'From: '.$from . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset='.$charset  . "\r\n";
$headers .= 'Reply-To: '.$from . "\r\n";
$headers .= 'X-Mailer: php';

In the above code, "From" and "MIME" lines are parsed correctly, but the later 3 lines are showing in the message body.

GMail is receiving it correctly.

Sithu
  • 4,752
  • 9
  • 64
  • 110

2 Answers2

2

Have you tried to use \n only instead of \r\n?

http://php.net/manual/en/function.mail.php

Note:

If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

You may use the code below to easy change of end of line in email:

$EEOL = "\n";
$headers  = 'From: '.$from . $EEOL;
$headers .= 'MIME-Version: 1.0' . $EEOL;
AnFi
  • 10,493
  • 3
  • 23
  • 47
  • Fantastic! It works. Do you know how can I check to use "\n" or "\r\n"? – Sithu Mar 14 '14 at 07:05
  • I use a PHP pre-defined constant [PHP_EOL](http://php.net/manual/en/reserved.constants.php#constant.php-eol) according to the answer http://stackoverflow.com/a/4415687/1179841 Thanks for your answer. – Sithu Mar 14 '14 at 07:16
0

You should consider using an email class library instead of the regular mail() function in php. I personally like the free SwiftMailer because of its simplicity and great functions for attachments etc.

Henkealg
  • 1,466
  • 1
  • 16
  • 19