使用standalone的actionmailer

ActionMailer與whenever搭配做電子報EDM的功能十分好用。以下介紹如何獨立使用actionmailer

參考以下程式碼:

require 'action_mailer'

設定信箱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => 'gmail.com',
:user_name => 'username',
:password => 'password',
:authentication => 'plain',
:enable_starttls_auto => true }
#這邊要注意的是virw_paths指的是目錄非檔案
ActionMailer::Base.view_paths = File.expand_path("#{Dir.pwd}/app/views/", __FILE__)
class InfoMailer < ActionMailer::Base
def send_to(list)
users = User.all
emails = users.collect{|u| u.email}
@url = set_url
@subject = "這個是標題!"
mail(to: emails, subject: @subject, from: sender) do |format|
format.html
end
end
private
#因為actionmailer不支援路徑設定
def set_url
Rails.env.production? ? "http://example.com" : "http://example.dev"
end
end