PJCHENder 未整理筆記

[Rails] Action Mailer Basic

2017-10-02

@(Ruby on Rails)[Ruby, RailsGuides]

[Rails] Action Mailer Basic

Generate Mailer

1
bin/rails g mailer AdminMailer

Create Mailer Controller

1
2
3
4
5
6
7
8
9
10
11
12
# ./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
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 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
1
2
3
4
5
6
7
8
9
<!--  HTML
./app/views/layouts/admin_mailer.html.erb
-->
<%= yield %>

<!-- TEXT
./app/views/layouts/admin_mailer.text.erb
-->
<%= yield %>
Partials
1
2
3
4
5
6
7
8
9
10
<!--  HTML
./app/views/admin_mailer/_user_summary.html.erb
-->

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

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

Preview

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

1
2
3
4
5
6
7
8
9
10
11
12
# ./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

1
2
3
4
5
6
7
8
9
10
# ./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 的位置:
1
2
3
# ./config/environments/production.rb

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

接著就可以於 Template 使用 image_tag

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

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

參考資料

Tags: rails

掃描二維條碼,分享此文章