跳至主要内容

[Rails] Action Mailer Basic

Generate Mailer

bin/rails g mailer AdminMailer

Create Mailer Controller

# ./app/mailers/admin_mailer.rb

class AdminMailer < ApplicationMailer
# default from: 'info@passer.cc'
layout 'admin_mailer'

def admin_email(subject, content)
@content = content

mail(subject: subject, to: Rails.application.secrets.admin_email_list)
end
end

View: Layout, Templates and Partials

Template
<!-- HTML
./app/views/admin_mailer/admin_email.html.erb
-->

<h3>Hello Rails Mailer</h3>
<%= render "user_summary", user: "Wavinfo Admin" %>

<!-- TEXT
./app/views/admin_mailer/admin_email.text.erb
-->

Hello Rails Mailer
<%= render "user_summary", user: "Wavinfo Admin" %>
Layout
<!--  HTML
./app/views/layouts/admin_mailer.html.erb
-->
<%= yield %>

<!-- TEXT
./app/views/layouts/admin_mailer.text.erb
-->
<%= yield %>
Partials
<!--  HTML
./app/views/admin_mailer/_user_summary.html.erb
-->

<h4>使用者資訊</h4>

<!-- TEXT
./app/views/admin_mailer/_user_summary.text.erb
使用者資訊
-->

Preview

建立 test 資料夾,但要注意這個資料夾並不在 app 資料夾內:

# ./test/mailers/previews/admin_mailer_preview.rb

class AdminMailerPreview < ActionMailer::Preview

def admin_email
# preview the mailer template in
# http://localhost:3000/rails/mailers/admin_mailer/admin_email.html
@content = "Hello"
AdminMailer.admin_email('Passer 測試信', @content)
end

end

Config

# ./config/environments/development.rb

# To preview mailer
config.action_mailer.preview_path = "#{Rails.root}/test/mailers/previews"

# Other Mailer Config
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :test
config.action_mailer.perform_deliveries = false

其他注意事項

在 Mailer 中使用圖片

  • 圖片在使用時不可使用 SVG。
  • 在 Rails 中可以設定 assets 的位置:
# ./config/environments/production.rb

config.action_mailer.asset_host = 'https://passer.cc'

接著就可以於 Template 使用 image_tag

<!-- ./app/views/layouts/order_mailer.html.erb -->

<%= image_tag 'logo.png', alt: 'Passer', style: 'height: 27px; width: 139px; margin: 0 auto;' %>

參考資料