日本語のメールを送信する

2011年4月3日

代々、Railsでの日本語メールはパッチを当てるか処理を書かないと、普段日本で流通しているメールの形式にはならない。

ようするに、エンコーディングが違うのである。

RailsでActiveMailを使って普通に送信すると、エンコーディングをUTF-8で送信してしまう。

ThunderBirdとかGMailとかだと、その辺を勝手に解釈して正常に表示されてしまうが

日本にはいまだにエンコードがUTF-8では正しく表示されないメーラーがあったりする。

これに対応するには、エンコーディングをUTF-8ではなく、ISO-2022-JPでメールを送る必要がある。

ということで、さっそく変換するためのパッチを入れる

http://d.hatena.ne.jp/hichiriki/20101026/1288107706

で公開されているコードを参考にmail_fix.rbファイルをconfig/initializersに入れる

#config/initializers/mail_fix.rb

require 'mail'

module Mail
  class UnstructuredField
    def encode_with_fix(value)
      encode_without_fix(value.encode(charset))
    end
    alias_method_chain :encode, :fix
  end

  class Message
    def charset=(value)
      @defaulted_charset = false
      @charset = value
      @header.charset = value
      @body.charset = value
    end
  end

  class Body
    def encoded_with_fix(transfer_encoding = '8bit')
      if multipart?
        encoded_without_fix(transfer_encoding)
      else
        be = get_best_encoding(transfer_encoding)
        dec = Mail::Encodings::get_encoding(encoding)
        enc = Mail::Encodings::get_encoding(be)
        if transfer_encoding == encoding and dec.nil?
          # Cannot decode, so skip normalization
          raw_source
        else
          # Decode then encode to normalize and allow transforming
          # from base64 to Q-P and vice versa
          enc.encode(dec.decode(raw_source).encode(charset))
        end
      end
    end
    alias_method_chain :encoded, :fix
  end
end

メール送信用のコードを作成する

rails g BuyListMailer

app/mailerディレクトリにbuy_list_mailer.rbファイルが作成される

このファイルを編集

# -*- coding:utf-8 -*-
class BuyListMailer < ActionMailer::Base
  default :from => "bousai@gendosu.jp", :charset => 'iso-2022-jp'
  def send_buy_list(user, buys)
    @buys = buys
    mail(:to => user.email, :subject => '買い物リスト')
  end
end

メールを送信するときは

コントローラなどで

BuyListMailer.send_buy_list(buys).deliver

とすれば、メールを送信できる。