How to decode an RFC 2047 encoded email header in Ruby?
I have the following header:
From: =?iso-8859-1?Q?Marta_Falc=E3o?= <marta.falcao@example.com.br>
I can easily split out the stuff before the <
, which leaves me with
"=?iso-8859-1?Q?Marta_Falc=E3o?="
What can I use to turn this int开发者_如何转开发o "Marta Falcão"
?
Using the newer Mail gem:
Mail::Encodings.value_decode(str)
or
Mail::Encodings.unquote_and_convert_to(str, to_encoding)
Thanks to Roland Illig for his comment, which led me to two options:
- install rfc2047-ruby and call
Rfc2047.decode(header)
- install TMail and call
TMail::Unquoter.unquote_and_convert_to(header, 'utf-8')
or better yetTMail::Address.parse(header).friendly
, the latter of which strips out the<email address>
part
Use Ruby to implement RFC 2047 isn't hard:
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
Update
mikel/mail is currently having an encoding issue which might not decode the string correctly.
If that really bothers you, you can try 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>
Since the source code of mikel/mail is a little too complicated for me to do the modification, I just made my own gem for this.
Gem source is here: https://github.com/tonytonyjan/rfc_2047/
精彩评论