LoginSignup
2
2

More than 3 years have passed since last update.

Rails / Ruby : Mail の HTML テキスト を取得する方法

Last updated at Posted at 2020-11-13

Rails で、 ActionMailer::Base を継承した Mailer クラス では mail というメソッドを使って メールオブジェクトを作成します。
その返り値のメールオブジェクトのメソッド deliver を呼び出すとメールが送信されます。

HTML をテキストとして取得

この HTML のメールの本文をテキストで取得する場合は次のようにメソッドを呼び出します。

mail.html_part.body.to_s

この html_part は Rails が使用している Gem mail で定義されています。

2020-11-14時点でのコード
    # Accessor for html_part
    def html_part(&block)
      if block_given?
        self.html_part = Mail::Part.new(:content_type => 'text/html', &block)
      else
        @html_part || find_first_mime_type('text/html')
      end
    end

Plain Text の本文を取得

Plain Text で取得する場合は text_part が使えます。

mail.text_part.body.to_s

.body までだと Body class のインスタンスが返ります。

関連

この記事では ActionMailer の mail メソッド の返り値から 本文を取得する方法について書いています。 送ったあとで本文を取得する場合は下記の記事が参考になります。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2