Inserting Newlines to Mail Body Programmatically in CakePHP 3

Inserting Newlines to Mail Body Programmatically in CakePHP 3

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
2 min read
CakePHP

Developers should ensure that each line in email body does not exceed one thousand bytes in length; otherwise garbled texts would be sent. This is specified by RFC 5321 and RFC 5322.

RFC Specification

RFC 5321 4.5.3.1.6. Text Line

The maximum total length of a text line including the is 1000 octets (not counting the leading dot duplicated for transparency). This number may be increased by the use of SMTP Service Extensions.

RFC 5322 2.1.1. Line Length Limits

Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF. … However, there are so many implementations that (in compliance with the transport requirements of [RFC5321]) do not accept messages containing more than 1000 characters including the CR and LF per line, it is important for implementations not to create such messages.

Solution

Because CakePHP 3 offers AbstractTransport class, developers can simply extend it, override send method, and write code to insert newlines into each line in the email body. This post does not cover this, so please refer to the official documentation for how to use the Transport feature.

To insert newlines at specific character counts, you can use Cake\Utility\Text::wordWrap which is designed to handle multibyte characters. By setting the fourth argument to true, newlines will be inserted even if word break occurs.

$message = 'hogefuga';
$result  = Text::wordWrap($message, 4, "\n", true);
// Result: "hoge\nfuga"
Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at KAKEHASHI Inc.
Involved in the design, development, and operation of the prescription data collection platform