使用操作Mailer - Rails 4向电子邮件添加附件

时间:2016-04-06 13:58:01

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2 ruby-on-rails-3.1

我有书名模型,有标题,page_no和描述。还有另一个模型Image。

class Book < ActiveRecord::Base
    has_many :images, dependent: :destroy
end 

class Image < ActiveRecord::Base
  belongs_to :book
end

我使用回形针上传图片。我需要在图书的展示页面中创建一个按钮,该按钮应该将所有图书的属性与图片一起发送到电子邮件中。为此,我将动作邮件编辑为:

rails g mailer BookMailer

并创建了app/views/book_mailer/booklist_email.html.erb

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>Welcome to Student Library</h1>
    <p>
      Book: <%= @book.title %>
    </p>
    <p>
      Page Number: <%= @book.page_number %>
    </p>
    <p>
      Description <%= @book.description %>
    </p>
    <p>
      Active <%= @book.active %>
    </p>
    <p>
      Please visit us again !!
    </p>
  </body>
</html>

此外,我将按钮放在书的展示页面中(views / books / show.html.erb)

<%= content_tag(:button, "Send Email", :type=>:submit)%>

booklist_email.html.erb

class BookMailer < ApplicationMailer
    default from: "unauthorized.testing@gmail.com"

    def booklist_email(book, email_id_to)
        @book = book
        mail(to: email_id_to, subject: 'List of Books with Images')
    end
end

现在,我应该如何在书籍节目页面点击按钮后触发电子邮件,该页面应该向任何用户发送电子邮件,这些用户应该在从书籍显示页面按下发送电子邮件按钮时给出电子邮件。如果我需要提供更多信息,请告诉我。我很困惑,我该怎么办。请帮忙

1 个答案:

答案 0 :(得分:0)

首先需要在BookMailer中创建一个方法,如果它尚未存在,并且要将所有参数发送给用户:

class BookMailer < ActiveMailer::Base
  def booklist_email(email, title)
    mail(from: 'me@me.com', to: email, subject: title)
  end

然后实际发送邮件:

BookMailer.booklist_email(@user.email, 'Hello customer!').deliver