Skip to content

Default encoding not able to transmit special characters #76

@stephtr

Description

@stephtr

The default encoding for addMessage is 7 bit / utf-8, which, as far as I know is kind of a contradiction. When sending mails including umlauts, in some email programs they are thus not displayed correctly.
The proper way would be to use:

msg.addMessage({ contentType: 'text/plain', data: quotedPrintableEncode(text), encoding: 'quoted-printable' });

But wouldn't it make sense to make this the default of MIMEText? eg.:

  • If encoding/charset is specified, use the text as-is.
  • If no encoding/charset is supplied, switch to quoted-printable and escape the text. As characters outside the 7-bit range are anyway illegal in the current state, this wouldn't even be a breaking change.

For reference, that's the function ChatGPT provided me and which works for me:

function quotedPrintableEncode(input: string): string {
    const encoder = new TextEncoder(); // encodes to UTF-8 bytes
    const bytes = encoder.encode(input);
    let result = '';
    let lineLength = 0;
  
    const softBreak = () => {
      result += '=\r\n';
      lineLength = 0;
    };
  
    for (let i = 0; i < bytes.length; i++) {
      const byte = bytes[i];
  
      // Printable ASCII range excluding '=' (equals)
      const isPrintable =
        (byte >= 33 && byte <= 60) || (byte >= 62 && byte <= 126);
  
      let toAppend;
  
      if (byte === 0x3D || !isPrintable) {
        // Needs encoding (e.g. "=" or non-printable)
        toAppend = '=' + byte.toString(16).toUpperCase().padStart(2, '0');
      } else {
        toAppend = String.fromCharCode(byte);
      }
  
      // Line length: soft wrap at 76 characters
      if (lineLength + toAppend.length > 75) {
        softBreak();
      }
  
      result += toAppend;
      lineLength += toAppend.length;
    }
  
    return result;
}

Great work btw!!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions