我有以下的头部信息:
From: =?iso-8859-1?Q?Marta_Falc=E3o?= <marta.falcao@example.com.br>
我可以轻松地分离出
<
之前的内容,这样就留下了"=?iso-8859-1?Q?Marta_Falc=E3o?="
我该用什么来把这个变成"Marta Falcão"?
我有以下的头部信息:
From: =?iso-8859-1?Q?Marta_Falc=E3o?= <marta.falcao@example.com.br>
<
之前的内容,这样就留下了"=?iso-8859-1?Q?Marta_Falc=E3o?="
Mail::Encodings.value_decode(str)
或者
Mail::Encodings.unquote_and_convert_to(str, to_encoding)
Rfc2047.decode(header)
TMail::Unquoter.unquote_and_convert_to(header, 'utf-8')
或者更好的选择是TMail::Address.parse(header).friendly
,后者会去掉<email address>
部分module Rfc2047
TOKEN = /[\041\043-\047\052\053\055\060-\071\101-\132\134\136\137\141-\176]+/.freeze
ENCODED_TEXT = /[\041-\076\100-\176]+/.freeze
ENCODED_WORD = /=\?(?<charset>#{TOKEN})\?(?<encoding>[QB])\?(?<encoded_text>#{ENCODED_TEXT})\?=/i.freeze
class << self
def encode(input)
"=?#{input.encoding}?B?#{[input].pack('m0')}?="
end
def decode(input)
match_data = ENCODED_WORD.match(input)
raise ArgumentError if match_data.nil?
charset, encoding, encoded_text = match_data.captures
decoded =
case encoding
when 'Q', 'q' then encoded_text.unpack1('M')
when 'B', 'b' then encoded_text.unpack1('m')
end
decoded.force_encoding(charset)
end
end
end
Rfc2047.decode '=?iso-8859-1?Q?Marta_Falc=E3o?=' # => Marta_Falcão
new_rfc_2047
:$ gem install new_rfc_2047
$ ruby -rrfc_2047 -e 'puts Rfc2047.decode "From: =?iso-8859-1?Q?Marta_Falc=E3o?= <marta.falcao@example.com.br>"'
From: Marta Falcão <marta.falcao@example.com.br>