[rails] Rails3.0 beta3のmailでiso-2022-jp
世の中だいぶUTF-8が浸透して文字化けもあまり見なくなった昨今ですが、
未だUTF-8化してない悩ましいものの一つに日本語メールがあります。
rails3のActionMailer(というよりかはmail gem)はだいぶ良くなったのですが、
まだそれができなかったのでモンキーパッチを書いちゃいました。
# encoding: utf-8 require 'mail' Mail::UnstructuredField.module_eval do def encode_with_fix(value) encode_without_fix(value.encode(charset)) end alias_method_chain :encode, :fix end Mail::Message.module_eval do def charset=(value) @defaulted_charset = false @charset = value @header.charset = value @body.charset = value end end Mail::Body.module_eval do def encoded_with_fix(transfer_encoding = '8bit') dec = Mail::Encodings::get_encoding(encoding) if multipart? || transfer_encoding == encoding and dec.nil? encoded_without_fix(transfer_encoding) else enc = Mail::Encodings::get_encoding(get_best_encoding(transfer_encoding)) enc.encode(dec.decode(raw_source).encode(charset)) end end alias_method_chain :encoded, :fix end
このファイルをconfig/initializers以下に例えばmail_encoding.rbとでもして置いておいて
mailerで
class Notifier < ActionMailer::Base default :from => ADMIN_EMAIL, :charset => 'iso-2022-jp' def signup(account) @account = account mail :to => @account.email, :subject => t('mail_subject_notifier_signup') end end
のようにしてやるとiso-2022-jpでエンコードされたメールが送信できます。
っていうかMail::Bodyにcharsetを渡してない時点でそれなりに酷いバグじゃないかとか思ったりもするわけですが。
ちなみにmultipartなメールのテストはしてないのでアシカラズ。