Skip to content

Instantly share code, notes, and snippets.

@sugamasao
Created October 26, 2010 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugamasao/646509 to your computer and use it in GitHub Desktop.
Save sugamasao/646509 to your computer and use it in GitHub Desktop.
Rail3 の Mail ライブラリ(mail)で ASCII文字 + JIS 文字がSubjectに入ってると死ぬ
==========
検証
==========
% cat mail.eml
Subject: hoge =?ISO-2022-JP?B?GyRCJUYlOSVIGyhC?=
Content-Type: text/plain; charset=ISO-2022-JP
Content-Transfer-Encoding: 7bit
sample
% rails c
> mail = Mail.read "mail.eml"
> mail.subject
=> Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ISO-2022-JP
===================
メモ
===================
mail.subject を呼ぶと、 header クラスの header['subject'] が呼ばれ、そこから
gems/mail-2.2.7/lib/mail/fields/unstructured_field.rb の default から do_decode が呼ばれて、最終的に
gems/mail-2.2.7/lib/mail/encodings.rb の Encodings.value_decode が呼ばれる。
ここでうまい事 Ruby 1.8.x / と Ruby 1.9 の互換性を保ちつつ、
Subject: hoge =?ISO-2022-JP?B?GyRCJUYlOSVIGyhC?=
のようなエンコーディングが複数になっている場合の対応を行わなければいけない。
=====================
修正箇所
デフォルトエンコーディング(大部分はUTF-8だと思うけど)に変更する
=====================
gems/mail-2.2.7/lib/mail/encodings.rb
module Mail
module Encodings
def Encodings.value_decode(str)
# ここの tap の部分を追加
end.tap do |words|
words.each do |word|
if word.is_a?(Array)
word.each do |w|
if(w.encoding != ''.encoding)
w.encode!(''.encoding, w.encoding)
end
end
elsif(word.encoding != ''.encoding)
word.encode!(''.encoding, word.encoding)
end
end
# ここまで
end.join("")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment