我写了一段代码,显示邮箱里邮件的主题,却不能显示汉字,如何解决?

我写了一段代码,显示邮箱里邮件的主题,却不能显示汉字,如何解决?

代码如下:
require 'net/pop'
Net::POP3.foreach('pop.163.com', 110, 'username', 'password') do |m|
  puts m.pop[/Subject:.+/]
  end

在命令行中运行的结果是:
Subject: =?gb2312?B?zfK148DtssbW1bbLMTDUwtbYtPPJ/by2xNrI3dSkuOajoQ==?=
Subject: =?GB2312?B?1+7QwtHQvr+2r8/yzajWqg==?=
Subject: =?GB2312?B?1+7QwrnJxrHGwLy2zajWqg==?=
Subject: =?GB2312?B?1+7QwrnJxrHGwLy2zajWqg==?=
Subject: =?UTF-8?B?5oKo5bey57uP6I635b6X5LqG5ZaA5ZqT?=
Subject: =?gbk?B?wfWhrM/Iyfo=?=
Subject: =?GB2312?B?1+7QwrnJxrHGwLy2zajWqg==?=
。。。。

各种编码(gb2312、gbk、utf-8)都有,如何正常显示中文呢?



[Copy to clipboard] [ - ]
其它几种编码,用iconv转换一下吧
try this:

require "rfc2047"

require 'net/pop'
Net::POP3.foreach('pop.163.com', 110, 'fsldn', 'sz073488') do |m|
   str = m.pop[/Subject:.*/]
   unless str.nil?
      puts Rfc2047.decode_to("utf8", str)
   else
      puts "Subject: <No Subject>"
   end
end

rfc2047.rb:

# $Id: rfc2047.rb,v 1.4 2003/04/18 20:55:56 sam Exp $
#
# An implementation of RFC 2047 decoding.
#
# This module depends on the iconv library by Nobuyoshi Nakada, which I've
# heard may be distributed as a standard part of Ruby 1.8. Many thanks to him
# for helping with building and using iconv.
#
# Thanks to "Josef 'Jupp' Schugt" <j...@gmx.de> for pointing out an error with
# stateful character sets.
#
# Copyright (c) Sam Roberts <srobe...@uniserve.com> 2004
#
# This file is distributed under the same terms as Ruby.

require 'iconv'

module Rfc2047

 WORD = %r{=\?([!#%$&'*+-/0-9A-Z\\^\`a-z{|}~]+)\?([BbQq])\?([!->@-~]+)\?=} # :nodoc:
 WORDSEQ = %r{(#{WORD.source})\s+(?=#{WORD.source})}

 # Decodes a string, +from+, containing RFC 2047 encoded words into a target
 # character set, +target+. See iconv_open(3) for information on the
 # supported target encodings. If one of the encoded words cannot be
 # converted to the target encoding, it is left in its encoded form.
 def Rfc2047.decode_to(target, from)
  return "" if from.nil?
  #puts "from: #{from}"
  from = from.gsub(WORDSEQ, '\1')
  #puts "gsub from: #{from}"
  out = from.gsub(WORD) do
  |word|
  charset, encoding, text = $1, $2, $3

  # B64 or QP decode, as necessary:
  case encoding
   when 'b', 'B'
    #puts text
    text = text.unpack('m*')[0]
    #puts text.dump

   when 'q', 'Q'
    # RFC 2047 has a variant of quoted printable where a ' ' character
    # can be represented as an '_', rather than =32, so convert
    # any of these that we find before doing the QP decoding.
    text = text.tr("_", " ")
    text = text.unpack('M*')[0]

   # Don't need an else, because no other values can be matched in a
   # WORD.
  end

  # Convert:
  #
  # Remember - Iconv.open(to, from)!
  begin
   text = Iconv.iconv(target, charset, text).join
   #puts text.dump
  rescue Errno::EINVAL, Iconv::IllegalSequence
   # Replace with the entire matched encoded word, a NOOP.
   text = word
  end
  end
 end
end