over 3 years ago

記錄如何做rails mailer

首先用rails generate出mailer

rails g mailer OrderMailer

然後編輯order_mailer.rb

app/mailer/order_mailer.rb
class OrderMailer < ActionMailer::Base
  default from: "example@artstore.dev"

  def compelete_notification(order, email)
    @order = order
    @email = email
    @link = order_url(@order)
    mail(to: @email, subject: "訂單:#{@order.id} 已成立。")
  end
end

view/order_mailer底下放text或是html的mail內容,如

compelete_notification.text.erb
訂單編號 <%= @order.id%> 已經成立
===============================================
總金額:<%= @order.total%> 
訂單細節:<%= @link %>

接下來要到config/environments/$RAILS_ENV.rb內設定

config/environments/development.rb
RocodevPractice::Application.configure do
  config.action_mailer.delivery_method = :letter_opener #你要用什麼寄, letter_opener 是測試用的gem


  config.action_mailer.default_url_options = {
    :host => "example.com"
  }
end

Production環境可以用mailgun gem

config/environments/production.rb
RocodevPractice::Application.configure do
  config.action_mailer.delivery_method = :mailgun
  config.action_mailer.mailgun_settings = {
    :api_key  => Setting.mailgun.api_key,
    :api_host => Setting.mailgun.api_host
  }

  config.action_mailer.default_url_options = {
    :host => Setting.domain.sub("http://", "")
  }
end
← [Rails Gem] Backround running Understand Rails Authenticity Token →
 
comments powered by Disqus