Ensuring Proper Line Breaks in Email Bodies with CakePHP 3

Ensuring Proper Line Breaks in Email Bodies with CakePHP 3

Takahiro Iwasa
Takahiro Iwasa
2 min read
CakePHP

Introduction

Developers should ensure that each line in an email body does not exceed one thousand bytes in length to prevent garbled text issues. This requirement is outlined in RFC 5321 and RFC 5322.

RFC Specifications

Text Line Limit in RFC 5321

RFC 5321 Section 4.5.3.1.6 states:

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.

Line Length Restrictions in RFC 5322

RFC 5322 Section 2.1.1 specifies:

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 RFC 5321) 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.

While some implementations may tolerate lines longer than this, adhering to these limits is critical for compatibility with transport requirements.

Solution: Inserting Newlines Programmatically

CakePHP 3 simplifies email handling through its AbstractTransport class. Developers can extend this class, override the send method, and implement code to enforce line-length constraints. For more details, refer to the official CakePHP documentation.

To insert newlines programmatically, use the Cake\Utility\Text::wordWrap method. This function supports multibyte characters and allows for controlled word wrapping by specifying the character limit and enabling forced line breaks.

Code Example

use Cake\Utility\Text;

$message = 'hogefuga';
$result  = Text::wordWrap($message, 4, "\n", true);
// Result: "hoge\nfuga"

By setting the fourth argument to true, newlines will be inserted even if word breaks occur, ensuring compliance with RFC standards.

Conclusion

When implementing an email-sending feature in CakePHP 3, always ensure that each line of the email body adheres to RFC 5321 and RFC 5322 standards. This practice guarantees compatibility across email clients and prevents garbled messages.

Happy Coding! 🚀

Takahiro Iwasa

Takahiro Iwasa

Software Developer at KAKEHASHI Inc.
Involved in the requirements definition, design, and development of cloud-native applications using AWS. Now, building a new prescription data collection platform at KAKEHASHI Inc. Japan AWS Top Engineers 2020-2023.