1

I'm using PHPMailer to send invoice emails. In some cases I get the undeliverable error of:

Your message contains invalid characters (bare line feed characters) which the email servers at something.com don't support.

There are other questions similar to this but none answer/solve my problem.

Like this: how to remove bare line feed characters using PHPMailer which does not have an answer.

After researching for few hour I came to conclusion that I have to replace LF ('\n') to CRLF ('\r\n').

I used the code below to replace any bare line feed characters to normalized line feeds in the email body and make it compliant to servers who does not accept bare line feeds. With the help of How to replace different newline styles in PHP the smartest way?

$body = preg_replace('~(*BSR_ANYCRLF)\R~', "\r\n", $body);
$body = preg_replace("#(?<!\r)\n#si", "\r\n", $body);
$body = preg_replace('~\R~u', "\r\n", $body);

Now:

after this change. Amount of undeliverable emails reduced, but the problem still exist. (getting undeliverable email couple times a week).

I thought this should work but I don't know how I'm still getting some undeliverable email errors when all the bare line feeds are replaced by the code above.

Note: Office 365 used to remove bare line feed characters before. But they changed it for security purposes.

Evik Ghazarian
  • 1,803
  • 1
  • 9
  • 24
  • Are you using PHPMailer 6.x or an older version? Are you sending via SMTP? – Synchro Nov 27 '19 at 07:01
  • I don't know how to see the version of the PHPMailer – Evik Ghazarian Nov 27 '19 at 16:40
  • @Synchro It's either 5.2.X or 5.6.X – Evik Ghazarian Nov 27 '19 at 16:42
  • Open the `src/PHPMailer.php` file and it will tell you. If you have a file called `class.phpmailer.php`, you're using a very old version. – Synchro Nov 27 '19 at 16:52
  • Yes, I have a class.phpmailer.php and the version is shown by public $Version = '5.2.7'; is this it? – Evik Ghazarian Nov 27 '19 at 16:55
  • @Synchro The public $LE = "\n"; shall I just change it to public $LE = "\r\n"; – Evik Ghazarian Nov 27 '19 at 16:58
  • That is a very old version from 2013; it's full of bugs and is vulnerable to several serious attacks. Don't touch the code, just update to the latest version. It always helps to [read the docs](https://github.com/PHPMailer/PHPMailer/wiki). – Synchro Nov 27 '19 at 17:01
  • @Synchro Thank you. Is there gonna be any obselete functions or changes I have to make? https://github.com/PHPMailer/PHPMailer/blob/master/UPGRADING.md says there are some to change. – Evik Ghazarian Nov 27 '19 at 17:04
  • 1
    You only need to make changes if you're using the things that are affected. The main thing that changes is how you load the files, which is covered in that doc and the readme. – Synchro Nov 27 '19 at 17:07

1 Answers1

0
$mailbody = preg_replace("/(\s*[\r\n]+\s*|\s+)/", ' ', $mailbody);

By doing so, I was able to solve the issue.

4b0
  • 21,981
  • 30
  • 95
  • 142