金子邦彦研究室プログラミングRuby プログラミングRuby で MIME エンコードと MIME デコード

Ruby で MIME エンコードと MIME デコード

Ruby を使って,MIME エンコードと MIME デコードを行うプログラム例を示す.

※ nkf については http://www.ruby-lang.org/ja/man/html/nkf.html


Ruby 1.9 系列の pack

a = 'hoge'
b = [a].pack("m0")
b.unpack("m0")

NKF の主要なオプション

プログラム例


#! ruby -Ks
# coding: windows-31j

require 'pp'
require 'nkf'

def mmencode(s)
  # 日本語を含む文書の encode 用途である.任意のバイナリデータの encode には Array::pack を推薦する
  # nkf を用いて base64 で MIME encode
  # nkf については http://www.ruby-lang.org/ja/man/html/nkf.html
  return NKF::nkf( '-sMB', s )
end

def mmdecode(s)
  # nkf を用いて base64 で MIME decode
  return NKF::nkf( '-smB', s )
end

if __FILE__ == $0
  # MIME encode と MIME decode の例
  # Windows の場合
  # FILENAME="C:\\hoge.txt"
  # Linux の場合
  FILENAME="/tmp/hoge.txt"
  # 念のためカレントディレクトリを変更しておく
  Dir.chdir( File.dirname( File.expand_path( FILENAME ) ) )
  File.open(FILENAME, "r") do |f|
    s = f.read
    pp s
    pp mmencode s
    pp mmdecode mmencode s
  end
end
実行結果の例

[image]

Ruby 1.9 系列での Base64 モジュール

エンコードの例

[image]

[image]

デコードの例

[image]

[image]