Skip to content

Instantly share code, notes, and snippets.

@takuo
Created January 21, 2010 09:14
Show Gist options
  • Save takuo/282683 to your computer and use it in GitHub Desktop.
Save takuo/282683 to your computer and use it in GitHub Desktop.
mime decode for ruby1.9
# mime decode for ruby 1.9
def mime_decode( input, out_charset = 'utf-8' )
while input.sub!(/(=\?[A-Za-z0-9_-]+\?[BQbq]\?[^\?]+\?=)(?:(?:\r\n)?[\s\t])+(=\?[A-Za-z0-9_-]+\?[BQbq]\?[^\?]+\?=)/, '\1\2')
end
begin
ret = input.sub!( /=\?([A-Za-z0-9_-]+)\?([BQbq])\?([^\?]+)\?=/ ) {
charset = $1
enc = $2.upcase
word = $3
word = word.unpack( { "B"=>"m*", "Q"=>"M*" }[enc] ).first
# Iconv.conv( out_charset + "//IGNORE", charset, word )
word.encode( out_charset, charset, :undef=>:replace, :invalid=>:replace )
}
return ret ? mime_decode( input ) : input
rescue
# "Error while convert MIME string."
return input
end
end
@Intrepidd
Copy link

You just saved my life. Isn't there a gem or something to do that in a better way?

Thanks anyway !

@ndbroadbent
Copy link

Wow, thanks a lot! This is the only thing I could find to help me decode mime encoded subjects from Gmail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment