How to handle UTF-8 email headers (like Subject:) using Ruby?

前端 未结 3 795
旧时难觅i
旧时难觅i 2021-01-05 04:04

I\'m an email n00b but I am working on an application that sends HTML email with Unicode characters (as my friend noted \"enjoy encoding hell\").

The Subject:<

3条回答
  •  自闭症患者
    2021-01-05 04:31

    Your can optionally do the same using Base64 encoding:

    require "base64"
    
    value  = Base64.encode64("Your UTF-8 string")
    header = "=?UTF-8?B?" + value + "?="
    

    Note the "B", that marks Base64 encoded payload, as opposed to the "Q" which marks "Q-encoded" payload. The latter could be faked by URL-encoding the string and replacing all "%" characters with "=".

    By "faking" I mean this: It would produce a valid result, but maybe more characters are encoded than would be necessary. The spec allows for encoding every character there is with "=" + ByteCodeAsHex, it merely impairs human readability of the raw headers. UrlEncode is + .gsub(/%/, "=") not a bad compromise when nothing else is available.

提交回复
热议问题