php mail() headers prevent email from sending

2019-07-13 08:00发布

问题:

I won't lie. I don't really understand some of the code I have used in the header for this mail function. I have been trying to fix it myself and some of the code is copied from other forum posts etc.

The $email, $subject, and $msg variables are all fine, and emails were sending when I tested them earlier with just these 3 vars. Then I added a header for the "From" section and the sender name was fixed (but emails went into my junk folder - annoying).

Now I am trying to add some html tags to the $msg and have used the last 2 lines on my $header variable as per other forum posts, but this has just stopped emails from getting sent at all. Please advise me on how to fix the issue.

$headers = "From: website <donotreply@website.com>" . PHP_EOL .
"BCC: customer1@hotmail.com" . PHP_EOL . 
"MIME-Version: 1.0 \r\n" . PHP_EOL . 
"Content-Type: text/html; charset=UTF-8' \r\n";

$email = "SomeEmail@hotmail.com";
$subject = "Weekly Newsletter";
mail($email, $subject, $msg, $headers);

Thanks guys I comment section for reminding me to post the error. It says:

Warning: mail(): Multiple or malformed newlines found in additional_header in /path/publishnewsletter.php on line 45

回答1:

"MIME-Version: 1.0 \r\n" . PHP_EOL . is too many newlines. Don’t use PHP_EOL at all; use \r\n, and only once.

You also have an extra single quote after charset.

$headers =
    "From: website <donotreply@website.com>\r\n" .
    "BCC: customer1@hotmail.com\r\n" . 
    "MIME-Version: 1.0\r\n" . 
    "Content-Type: text/html; charset=UTF-8";


回答2:

Look at this it might help:

  • Sanitize your headers. No multiple newlines in additional_headers argument. These count as "multiple or malformed newlines": \r\r, \r\0, \r\n\r\n, \n\n, \n\0.
  • Use additional_headers for headers only. Email message (multipart or not, with ir without attachments, etc) belongs in message argument, not in headers.
  • And DO NOT use PHP_EOL

PHP Security Bug report: https://bugs.php.net/bug.php?id=68776
C Code diff how its fixed: http://git.php.net/?p=php-src.git;a=blobdiff;f=ext/standard/mail.c;h=448013a472a3466245e64b1cb37a9d1b0f7c007e;hp=1ebc8fecb7ef4c266a341cdc701f0686d6482242;hb=9d168b863e007c4e15ebe4d2eecabdf8b0582e30;hpb=eee8b6c33fc968ef8c496db8fb54e8c9d9d5a8f9