Rails3でiso2022jpメールを送る

Pocket

ruby1.8.7で動作を確認。
initializersの下に適当なファイル名でいれておく。

require 'mail'

Mail::UnstructuredField.module_eval do
  def encode_with_fix(value)
    encode_without_fix(Kconv.tojis(value))
  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(Kconv.tojis(dec.decode(raw_source)))
    end
  end
  alias_method_chain :encoded, :fix
end

このままだとsubjectが文字化けするので以下のクラスを
iso2022jp_mailer.rbとでもしてapp/mailers以下にいれておく。

class Iso2022jpMailer < ActionMailer::Base
  def default(value = nil)
    unless value[:charset]
      value[:charset] = 'iso-2022-jp'
    end
    super(value)
  end

  def mail(headers={}, &block)
    headers[:charset] = 'iso-2022-jp'
    if headers[:subject]
      headers[:subject] = Kconv.tojis(headers[:subject])
    end
    super(headers, &block)
  end
end

使い方

# Mailerクラス
class Mymailer < Iso2022jpMailer
  default :from => "from@example.com"


  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.mymailer.index.subject
  #
  def index(params)
    @params = params
    @greeting = "Hi"

    mail :to => "to@example.org", :subject => 'メールサブジェクト'
  end
end

# 呼び出し元のコントローラ
Mymailer.index(:username => '野口').deliver

投稿者紹介

株式会社ユニキャスト
私たちは、テクノロジに魅せられた個性あふれるメンバーによって構成された茨城県日立市に本社を構えるベンチャー企業です。
”テクノロジを通して「驚き」と「感動」を創造し、人々の「夢」と「笑顔」を支えます。” の経営理念をモットーに明るい未来を描き、ワクワクする企画提案を続けて参ります。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください