2015年1月19日月曜日

RailsでActionMailerでファイルを添付する方法

ブラウザから、アップロードされたファイルをメールに添付して送信するようなことを想定しています。

Actionでのメール送信メソッド

送信用 アクションメソッドは以下のようになります。
tmp_file はFile.class のオブジェクトを受け取る想定です。

  def send_mail

    to_mail = params['to_mail']
    tmp_file = params['tmp_file']

    SendsMailer.send_mail(to_email, tmp_file).deliver

  end

ActionMailerの実装

ActionMailerは以下のようになります。

# -*- encoding : utf-8 -*-
class SendsMailer < ActionMailer::Base

  default :from => 'from@example.com', :content_type => 'text/html'

  def send_mail(to_mail, tmp_file = nil)
    attachments[tmp_file.original_filename] = File.read(tmp_file.path) if tmp_file.present?

    mail(:to => to_mail,
         :subject => "メール送信テスト")
  end

end

重要な部分は

attachments[tmp_file.original_filename] = File.read(tmp_file.path)
attachments['ファイル名'] = 添付するファイル

0 件のコメント:

コメントを投稿

statistics