Why improper header field folding breaks email API requests

You’ve double-checked your API payload. The JSON is valid. The authentication headers look right. But the email still fails to send—no error, no log, just silence.

That’s not a server issue. It’s likely a hidden syntax violation: improperly folded long header fields. MIME headers in email must follow strict formatting rules. Break them, and even a single misplaced line break can invalidate the entire message.

Imagine sending a letter with a perfectly written address—but folding the paper so the lines run off the edge. The post office won’t reject it for content, but for form. Same with email: RFC 5322 specifies exact rules for how long header fields should be folded. Violate those, and the mail server rejects you outright.

Key takeaways

  • Long header fields must be folded at 78 characters using a soft line break, not just any newline.
  • Improper folding—like breaking a MIME boundary or authentication token—renders the message syntactically invalid.
  • Even if your payload is structurally correct, incorrect line breaks in headers will cause delivery failure or spam filtering.

What is header field folding, and when does it matter?

Header field folding splits a long email header into multiple lines using a line break followed by a space or tab, ensuring compliance with RFC 5322’s 998-character limit per line. It matters when headers—like authorization tokens or tracking URLs—exceed that limit, causing SMTP servers to reject or misinterpret messages. You must implement it correctly in APIs that send email via SMTP or HTTP (e.g., SendGrid, Mailgun) to prevent delivery failure or security issues.

How RFC 5322 defines the line-length limit

Per RFC 5322, no line in an email message—this includes headers—can exceed 998 characters. This isn't a suggestion; it’s a hard requirement for all compliant mail servers. If your API sends headers with long values, such as URLs or encrypted tokens, and fails to fold them properly, the server may silently drop the message or flag it as malformed.

When header folding becomes a real issue in email APIs

You encounter this problem when you embed long, dynamic data in headers—like custom tracking IDs, OAuth2 tokens, or deeply nested marketing parameters. For example, a tracking URL in a Content-Location header might easily exceed 998 characters if combined with multiple query parameters. Without proper folding, the message will be rejected by strict mail servers.

Let’s say you're using an email API to send transactional messages. Your Reply-To or Authentication-Results header contains a token from a third-party service. If that token is not folded when it hits 998 characters, the server will see it as invalid. Some systems even treat non-folding as a sign of injection attempts, leading to spam filtering or outright rejection. This isn’t theoretical—it’s enforcement standard across modern mail transport systems.

Many email service providers (ESPs) like SendGrid or Mailgun handle folding internally when you use their SDKs. But if you're building a custom integration, especially over SMTP or HTTP, you must do it yourself. Tools like the Email Verification API help you validate and clean addresses before sending, but they don’t manage header formatting. That responsibility falls on your codebase.

Use a line break followed by a single space or tab (SP or HTAB) to continue a header field. Never break mid-word or skip the leading whitespace. The receiver is required to reassemble these lines into the original value. Misusing folding—like adding newlines without whitespace—results in corrupted headers and broken messages.

For deeper reading, see the official specification in RFC 5322 section 2.1.1, which defines the syntax rules for header fields and message lines. While RFC 5322 is decades old, its line-length limits remain unchanged and are implemented by all modern email infrastructure.

How to properly fold header fields in email API requests

You must begin folding email header fields only after 998 characters, insert a line break immediately after the 998th character, then add a single SP (space) or HTAB (tab) as a continuation character. Folding must occur only at valid whitespace boundaries—never within a quoted string, base64 value, or URL. The receiving system reassembles the field by stripping all whitespace following a fold and rejoining the lines. This ensures compliance with RFC 5322 and avoids parsing errors in email infrastructure.

The 998-character rule and fold placement

SMTP and email standards define a maximum line length of 998 characters. Exceeding this triggers protocol violations, potentially causing rejection or delivery failure. You don't need to fold earlier—doing so wastes bandwidth and increases complexity without benefit. The fold itself must happen right at the 998th character, followed by a single space or tab. This spacing acts as a signal that the line continues.

Where and when to fold: boundary rules

Folding must occur only at whitespace that separates tokens. Never break a quoted string, a base64-encoded value, or a URL middle. For example, folding inside "[email protected]" or a Content-Type: text/html;charset=UTF-8 header value causes parsing failures. Always check that the fold point comes after a space, tab, or newline, and before a non-whitespace character.

  1. Measure the full header field. Don't assume line length—count bytes, not characters, especially with UTF-8. A single emoji or accented character may count as multiple bytes.
  2. Start folding at character 998, not earlier. There's no performance gain in folding earlier, and it increases the risk of invalid splits.
  3. Insert a single space or tab after the 998th character. This is the mandatory continuation character. Use SP (space) unless your system or client requires HTAB (tab)—SP is more universally accepted.
  4. Only fold at valid whitespace boundaries. Never split a token: a quoted string, a base64 line, or a URL path element. Use a parser-aware method to detect token edges.
  5. Reconstruct on the receiving side. Strip all whitespace that follows a fold and join the lines. The original field value must be reassembled exactly as sent, with no data loss.

For reference, see RFC 5322, Section 2.1.1, which defines the syntax and line length limits for email headers. Tools like Internet Mail (RFC 5322) provide the definitive specification.

Common mistakes when folding header fields

You’re likely breaking email headers if you’re inserting line breaks between non-whitespace characters (like after an '=' in a parameter), using multiple spaces as fold indicators, hard-coding a 78-character limit, or folding inside quoted strings. These mistakes trigger parsing errors, trigger spam filters, and break deliverability—even if your API logic is sound. RFC 5322 defines the rules; ignoring them is a common, avoidable flaw in email infrastructure. Reliable systems like those used by major email providers strictly enforce them.

When folding goes wrong

  • Inserting a line break between two non-whitespace characters (e.g., Content-Type: text/html; charset=UTF-8 split as Content-Type: text/html; c
    harset=UTF-8
    ) breaks the syntax and confuses parsers.
  • Using multiple spaces as a fold indicator (e.g., more than one space after a line break) is invalid. Only a single CRLF followed by exactly one SP or HT is permitted.
  • Fixating on a 78-character limit (a legacy from 1982) isn't accurate for modern systems. While some older tools still enforce it, most modern email services accept longer lines as long as the folding is correct.
  • Folding inside a quoted string—such as in Content-Type: text/html; charset="UTF-8" split as Content-Type: text/html; charset="U
    TF-8"
    —breaks the quoted-value structure, rendering the header malformed.

Why it matters for deliverability

Malformed headers aren't just ignored—they’re a red flag. Email systems with strict validation (like modern enterprise gateways and ISPs) may reject messages or mark them as spam. Even if your code passes basic checks, incorrect folding can trigger greylisting or reputation penalties. A small error here can affect inbox placement rates across domains.

When building or debugging email APIs, treat header folding not as a formatting preference but as a critical parsing requirement. Tools like our real-time verification API can help ensure your headers and overall email infrastructure meet strict technical standards before going live.

The root issue often isn't complexity—it’s assuming old rules still apply. Stick to RFC 5322’s defined folding rules: fold only after a CRLF, followed by exactly one whitespace character, and only between tokens or within a parameter value (not inside quotes or identifiers). A few missteps here can silently degrade your sending performance across major inboxes.

For deeper validation of email infrastructure, including header structure and format, our inbox placement testing simulates delivery through multiple provider environments.

When header folding fails silently

You might think a correctly folded header is safe—but some email servers accept malformed headers without error, only to silently alter or drop parts of them. This leads to inconsistent behavior, especially when messages pass through multiple gateways, and can trigger spam filters that flag non-standard headers as suspicious. Even small errors in line breaks or continuation spacing can result in delivery failures you won’t see until a message disappears into a spam folder.

Why servers accept broken headers

Many mail servers are built to be tolerant of minor header irregularities to maintain compatibility with older or poorly written clients. This leniency means your API request might be accepted, but the content could be truncated, reformatted, or lost entirely during transit. The problem is, you won’t know it failed unless you monitor delivery outcomes closely across different recipient domains.

For example, a header field that exceeds 78 characters without proper line continuation might still be processed, but the server may silently trim beyond that limit. This is particularly risky when sending through intermediary systems like cloud-based email relays or bulk mailing platforms, where intermediate parsing steps can introduce unexpected transformations.

How misfolded headers impact deliverability

Even when messages reach their destination, misfolded headers can harm sender reputation. Systems like Spamhaus and Google’s Postini evaluate message structure as part of their spam scoring. Headers that deviate from RFC 5322 standards—especially those with improper continuation lines—are often flagged as suspicious, increasing the chance of inbox placement issues or outright rejection.

Consider this: a header that wraps incorrectly in a request to an email API might still be accepted by the first hop, but a later relay may drop it silently. The result? Recipients receive incomplete or malformed headers—potentially leading to delivery failure or filtering. This isn’t a binary “work or fail” problem; it’s intermittent behavior that’s hard to debug without detailed logging.

Let’s be clear: you can’t rely on servers to correct your formatting. The safest path is to follow the protocol exactly. Use a single CRLF (carriage return + line feed) after the 78th character, followed by a single space for continuation lines. This ensures consistent behavior across all compliant systems. For more on email standards, see the official Internet Message Format specification.

If you’re building or debugging email APIs, validating header structure before sending is critical. Use tools that test full email envelopes with known edge cases—like inbox placement testing—to surface hidden delivery risks before they impact your audience.

How Emaillistchecker.io helps validate email delivery readiness

You can't assume headers are properly folded just because they're syntactically valid. Emaillistchecker.io’s real-time verification API checks for structural correctness in email payloads, including header folding compliance per RFC 5322. Our inbox-placement testing simulates actual server behavior, surfacing misfolded headers before you send. This stops bounces, filters, and delivery failures before they happen—especially critical for APIs where malformed input breaks automation.

Header Folding Compliance and Real-World Delivery Testing

Long headers in email APIs must be folded correctly: line breaks inserted at 78 characters or less, with whitespace after a line break. The difference between a proper fold and a misfold is not just academic—it alters how receiving servers read your message. Misfolded headers can trigger rejection by strict filters or cause content corruption. Emaillistchecker.io checks both syntax and context, ensuring your header structure is safe for all major mail servers.

Our inbox-placement tests don’t just check if a message arrives—they validate how it arrives. By sending test messages to real inboxes across Gmail, Outlook, and Yahoo, we detect if misfolded headers cause unexpected behavior. Some servers drop or reformat incorrectly folded headers silently. The only way to catch this is by simulating real delivery environments, which our testing covers.

Risk Detection Built Into Every Verification

Beyond header format, our API flags deliverability risks that often slip past basic email checks. Role accounts (like admin@, support@) tend to be ignored or filtered. Disposable domains are often blocked outright. And expired IPs in shared or poorly managed infrastructure can sink your sender reputation.

Our verification process includes checks against real-time blocklists and known bad patterns. These checks run in parallel with header validation, providing a holistic readiness score. If your message contains a malformed header or references a high-risk recipient, you get a clear alert — so you can fix it before your campaign runs.

For teams using APIs at scale, this layer of validation cuts down on delivery surprises. You can run bulk validations with bulk verification or integrate directly via our real-time verification API, ensuring every request complies with SMTP and MIME standards. This isn’t just about syntax—it’s about inbox placement, reputation, and deliverability certainty.

Folding examples: valid vs. invalid

When you send an email API request, long header fields like X-Auth-Token must be folded correctly: break the line after a CRLF, then indent with exactly one SP or HT. Invalid folding—using no space, multiple spaces, or breaking mid-value—causes parsing errors. The correct way ensures compatibility with RFC 5322, which standardizes message syntax. A malformed header may fail silently in production, leading to authentication failures.

Correct vs. incorrect folding patterns

Let's walk through real examples of what works and what doesn't. The key is line continuation syntax: a newline followed by exactly one space or tab, not more and not less.

Example Valid? Why
X-Auth-Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
Yes Properly folded: CRLF followed by one SP. Line breaks between tokens maintain structure.
X-Auth-Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
No Uses five spaces. Over-indentation violates RFC 5322’s "one or more" space rule, which requires exactly one SP or HT. Many servers reject this.
X-Auth-Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
No No whitespace after the newline. Missing the required space or tab. This is a syntax error and breaks parsing.

For real-world validation, tools like RFC 5322 define line folding explicitly. In practice, many HTTP clients and email servers enforce these rules strictly. Libraries like HTTP parser reject headers that don’t follow this rule.

To prevent mistakes when building API requests, especially with JWTs or other long tokens, use automated validators. You can test your header format in real-time with our email verification API, which handles header validation as part of message parsing checks. This helps you catch formatting errors before deployment.

Tools that automatically handle header folding

Most modern email libraries handle header folding automatically when you assign headers correctly—no manual line breaks needed. You just set the header value, and the library ensures it adheres to RFC 5322’s 78-character limit by inserting soft line breaks where appropriate, as long as you don’t manually insert newlines during composition.

Native libraries do the work for you

Libraries like Python’s email module, Java Mail, and Node.js’s mailgun-js are designed to handle folding internally. When you use them to build email headers, they’ll break long values at valid points—usually between words or after commas—without needing your input. Let’s say you’re setting a Subject header with a long phrase: these tools will fold it correctly, so it fits within the 78-character line limit.

Using them correctly means avoiding direct string concatenation with line breaks in your header values. If you manually insert \r\n or break a header into multiple lines, you risk breaking parsing, especially if mail servers or clients don’t expect it. That’s where manual folding fails most often.

SMTP clients and manual folding

SMTP clients that don’t abstract away the wire format—like custom-built API handlers—must be careful. If you build a message string by hand and insert newlines in the header body, you’re likely to trigger a rejection or misinterpretation. The SMTP server expects headers to be on single lines, with folding represented as soft breaks, not hard ones.

Any custom API-based client must validate header line lengths against RFC 5322, section 2.2.1, which defines the maximum line length. You must ensure no line exceeds 998 characters, and folded lines start with a space or tab. You can test your output using open-source tools like Exim, Postfix, or even Microsoft Exchange, as they all follow the standards. Even small errors—such as breaking a header mid-phrase or using a single whitespace—can lead to delivery failure.

For teams building on top of SendGrid, Mailgun, or similar platforms, you’re usually safe. These APIs handle the folding internally when you use their official SDKs. But when you bypass those and send raw SMTP, the rules apply. Always double-check by testing your full headers through RFC 5322 and validating output against real-world mail servers.

If you’re managing large-scale email sending and want to ensure your headers—and your recipients—are valid, consider verifying your list first. Bulk verification helps eliminate invalid addresses before delivery, which reduces the risk of misconfigured headers being flagged as spam or rejected outright.

Testing your email API request headers before deployment

You can validate header structure, test real-world deliverability, and inspect raw output to catch folding issues before they cause bounces or misdelivery. Use tools to verify syntax, run inbox tests with actual mail servers, and log sent messages to ensure your headers remain intact through transport.

Verify syntax with dedicated tools

  • Use MxToolbox or Mail-Tester to check header structure and syntax before sending.
  • Look for unstructured or improperly folded long header fields; these often cause rejection by strict mail servers.
  • Ensure each line after the first in a folded header starts with a space or tab — this is required by RFC 5322.

Test real inbox behavior with inbox-placement features

  • Run deliverability tests using inbox-placement testing to see how major providers like Gmail, Outlook, and Yahoo interpret your message.
  • These tools simulate real mail server behavior and highlight issues with field folding, length, or formatting that aren’t caught by basic syntax checks.
  • Test with actual domains — not just your own — to catch inconsistencies across different mail server implementations.

Inspect raw message output after sending

  • Log the raw message data (including headers) after sending through your API to compare with intended structure.
  • Check that long fields like Content-Type, Return-Path, or Received are properly folded across multiple lines with indentation.
  • Look for silent corruption — headers that appear correct in code but are mangled in transit due to improper folding.

The bottom line: prevent failures by respecting standards

Email headers must be folded correctly when values exceed 998 characters. Failing to do so breaks SMTP protocols and can cause delivery failures.

A single misfolded header can trigger spam filters, disrupt automation workflows, or result in undelivered messages. This is not a minor formatting issue — it's a protocol violation with measurable consequences.

Respecting RFC 5322 standards ensures compatibility across mail servers, maintains sender reputation, and supports consistent inbox placement. Proper folding is a non-negotiable part of reliable email delivery.

Sources

Keep reading

Ready to put this into practice? Emaillistchecker.io verifies emails with 98.9% accuracy — start with 100 free verifications.

Frequently asked questions

What happens if I don't fold long email headers?

Servers may reject the message, silently truncate content, or flag it as spam. Misfolded headers violate RFC 5322 and are a common cause of delivery failure.

Is there a limit to how many times I can fold a header?

No — you can fold a header multiple times, as long as each fold starts with a single SP or HTAB and occurs only after a natural line break.

Can a single line break in the middle of a token cause problems?

Yes — breaking tokens like base64 values, URLs, or quoted strings can invalidate the entire header. Always fold at whitespace boundaries.

Do email APIs like SendGrid or Sendinblue handle folding automatically?

Yes, when using their official libraries. But if you're building a custom client, you must handle folding yourself to avoid syntax errors.

How do I test if my headers are properly folded?

Send test emails through Emaillistchecker.io’s inbox-placement tool or analyze the raw message via tools like MxToolbox or a local SMTP relay.

What’s the difference between SP and HTAB in header folding?

SP (space) and HTAB (tab) both act as continuation markers, but SP is more widely supported. Use SP unless your system specifically requires HTAB.

Does folding affect the content of the header value?

No — when properly folded and parsed, the recipient server reconstructs the original value exactly as intended.

Can misfolded headers be detected by spam filters?

Yes — malformed headers are a known red flag. Spam filters often flag messages with suspicious syntax, including improper folding, as high-risk.

Should I use 78 or 998 character limits for folding?

Use 998 — the 78-character limit is outdated. Modern mail systems use 998 as the maximum line length for a message line.

How does Emaillistchecker.io help with header folding issues?

Our inbox-placement testing checks for syntax errors in headers, including misfolded values, and reports deliverability risks before you send.