Skip to content

fix(smtp-server): encode subject to UTF-8 before database insertion#3594

Open
DamienLGRCA wants to merge 1 commit into
postalserver:mainfrom
DamienLGRCA:fix/encode-subject-utf8
Open

fix(smtp-server): encode subject to UTF-8 before database insertion#3594
DamienLGRCA wants to merge 1 commit into
postalserver:mainfrom
DamienLGRCA:fix/encode-subject-utf8

Conversation

@DamienLGRCA

Copy link
Copy Markdown

Problem

Emails with subjects containing raw non-UTF-8 characters (e.g. ISO-8859-1 \xE9 for "é") without RFC 2047 MIME encoding cause Mysql2::Error: Incorrect string value during insertion into the messages table. The email is silently dropped — never delivered to the endpoint.

This is an issue that has existed since at least 2021 (see #1636). In environments receiving mail from legacy systems (ERPs, invoicing software), this can affect hundreds of emails per day.

Root cause

In lib/postal/message_db/message.rb, the subject is extracted via headers["subject"]&.last.to_s[0, 200] and inserted as-is. The Mail gem's field.decoded correctly handles RFC 2047 encoded headers (=?ISO-8859-1?Q?...?=), but when the sender does not encode the subject per RFC 2047 (raw ISO-8859-1 bytes), the string is passed through unchanged. MySQL in strict mode then rejects the invalid UTF-8.

Fix

Added a private encode_utf8 method that safely converts the subject to valid UTF-8:

  1. No-op if already valid UTF-8
  2. Re-interprets bytes as UTF-8 if possible
  3. Falls back to ISO-8859-1 → UTF-8 conversion (most common case for European accented characters)
  4. Last resort: replaces invalid characters with ?

Reproduction

# Send an email with raw ISO-8859-1 subject (\xE9 = é)
printf 'Subject: Facture/note de cr\xe9dit Nr 12345\r\n' | # via SMTP to Postal

Results in:

Mysql2::Error: Incorrect string value: '\xE9dit N...' for column \`postal-server-1\`.\`messages\`.\`subject\` at row 1

Closes #1636

Emails with subjects containing non-UTF-8 characters (e.g. ISO-8859-1
encoded accented characters like 'é' as raw \xE9) cause a
Mysql2::Error 'Incorrect string value' when Postal attempts to insert
the message into the database. This results in the email being
silently dropped.

This commit adds an encode_utf8 helper that:
1. Returns the string as-is if already valid UTF-8
2. Attempts to re-interpret bytes as UTF-8
3. Falls back to ISO-8859-1 to UTF-8 conversion (most common case
   for European accented characters)
4. As a last resort, replaces invalid characters with '?'

This fixes the issue reported in postalserver#1636 where emails sent with
ISO-8859-1 encoded subjects without RFC 2047 MIME encoding are
rejected by MySQL.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mysql2::Error: Incorrect string value: '\xE9..' for column postal-server-4.messages.subject at row 1

2 participants