Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to decode q-encoded strings in Ruby?

I'm working with mails, and names and subjects sometimes come q-encoded, like this:

=?UTF-8?Q?J=2E_Pablo_Fern=C3=A1ndez?=

Is there a way to decode them in Ruby? It seems TMail should take care of it, but it's not doing it.

like image 342
pupeno Avatar asked Dec 16 '22 22:12

pupeno


2 Answers

I use this to parse email subjects:

You could try the following:

str = "=?UTF-8?Q?J=2E_Pablo_Fern=C3=A1ndez?="
if m = /=\?([A-Za-z0-9\-]+)\?(B|Q)\?([!->@-~]+)\?=/i.match(str)
        case m[2]
        when "B" # Base64 encoded
          decoded = Base64.decode64(m[3])
        when "Q" # Q encoded
          decoded = m[3].unpack("M").first.gsub('_',' ')
        else
          p "Could not find keyword!!!"
        end
        Iconv.conv('utf-8',m[1],decoded) # to convert to utf-8
end
like image 177
ankimal Avatar answered Dec 19 '22 10:12

ankimal


Ruby includes a method of decoding Quoted-Printable strings:

puts "Pablo_Fern=C3=A1ndez".unpack "M"
# => Pablo_Fernández

But this doesn't seem to work on your entire string (including the =?UTF-8?Q? part at the beginning. Maybe you can work it out from there, though.

like image 25
jtbandes Avatar answered Dec 19 '22 11:12

jtbandes