Skip to content

Instantly share code, notes, and snippets.

@pauljm
Created September 17, 2015 23:34
Show Gist options
  • Save pauljm/8c73a6581717acdf3eea to your computer and use it in GitHub Desktop.
Save pauljm/8c73a6581717acdf3eea to your computer and use it in GitHub Desktop.
Strategy for handling non-ASCII with Mail
# Escape non-ASCII characters and forward slashes as unicode escape sequences,
# but with forward slashes instead of backslashes, since backslashes already have meaning
def asciiify(str)
str.unpack('U*').map { |i|
(i == 47 || i == 92 || i > 127) ? "/u" + i.to_s(16).rjust(4, '0') : i.chr
}.join
end
# Decode "forward slashed" unicode escape sequences
def deasciiify(str)
str.gsub(/\/u([\da-fA-F]{4})/) { |m|
[$1].pack("H*").unpack("n*").pack("U*")
}
end
raw = "Abé Allen <a@a.com>, 粗楷体简 <b@b.com>, c@c.com, //// <hi@hi.com>"
list = Mail::AddressList.new(asciiify(raw))
puts deasciiify(list.addresses[1].format) # 粗楷体简 <b@b.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment