Email: maximum length of a text line

From RFC 2821 (Simple Mail Transfer Protocol, April 2001). The maximum total length of a text line including the is 1000 characters (not counting the leading dot duplicated for transparency).
This number may be increased by the use of SMTP Service Extensions.

// Normalize the line breaks so we know the explode works
$body = str_replace("\r\n", "\n", $body);
$body = str_replace("\r", "\n", $body);
 
$lines = explode("\n", $body);
$max_line_length = 998;
$body = '';
while (list(,$line) = @each($lines)) {
  $lines_out = null;
  // Ok we need to break this line up into several smaller lines
  while (strlen($line) > $max_line_length) {
    $pos = strrpos(substr($line,0,$max_line_length)," ");
 
    // Patch to fix DOS attack
    if (!$pos) {
      $pos = $max_line_length - 1;
      $lines_out[] = substr($line,0,$pos);
      $line = substr($line,$pos);
    } else {
      $lines_out[] = substr($line,0,$pos);
      $line = substr($line,$pos + 1);
    }
  }
  $lines_out[] = $line;
 
  while (list(,$line_out) = @each($lines_out)) {
    if (strlen($line_out) > 0) {
      if (substr($line_out, 0, 1) == ".") {
        $line_out = "." . $line_out;
      }
    }
    $body .= $line_out . "\r\n";
  }
}

Leave a Reply