精華區beta Ruby 關於我們 聯絡資訊
出自我的 Blog http://lightyror.blogspot.com/2006/09/actionmailer-sendmail.html Action Mailer 是 Ruby on Rails 上面收發信的機制 不過因為收信實在牽涉到太多東西 我們先不予以探索,只論發信的機制 就算是寄信,也有很多方式 可以用 SMTP Server 來寄 但是也要設定很多東西 身為 Rails Programmer ,而非網管 我們先使用最最最簡單的 sendmail 來寄信 測試Sendmail 要用寄信前,請先在命令列上打 sendmail [email protected] 等到他出現下一行 就可以亂打一些內容 然後按下 Ctrl + D 寄出 麻煩請記住 如果連手動使用 sendmail 都寄不出去 代表你現在的機器寄信機制上面有問題 ActionMailer 更不可能記得出去 如果你的機器上面沒有 sendmail 指令 請按照這個網頁安裝 Postfix 使用 ActionMailer 如果您想要繼續看這一章 麻煩請先把上一章測試成功 上一章 sendmail 測試不成功,這一章是不可能成功的 設定 要設定 ActionMailer ,請到 config/enviroments/ 修改你現在環境的設定檔 ActionMailer::Base.delivery_method = :sendmail ActionMailer::Base.default_content_type = 'text/html' 第一行是告訴我們寄信的機制是用 sendmail ( 預設是 smtp ) 第二行是告訴我們寄信的內容是以 HTML 格式來寄的 (預設是 plain text) 產生 Mailer Mailer 在 Rails 裡面地位跟 Model 一樣 我們都是使用 ruby script/generate mailer 你要的mailer名字 來產生 Mailer 填寫內容 產生出來的 Mailer 會在 model 層裡面產生一個 class MyMail < ActionMailer::Base end 我們可以加入一些 Method class MyMail < ActionMailer::Base def send_mail( user ) # Email header info MUST be added here @recipients = '[email protected]' @from = "[email protected]" @subject = "測試標題許功蓋" end end 我們剛剛的 method 還沒有填寫內容 如果你眼尖一點 你會發現 Generator 會幫你在 view 裡面產生相關 Mailer 的目錄 沒錯 Mailer 裡面他也把 MVC 切的清清楚楚的 我們剛剛撰寫一個 send_mail method 我們就必須跑到相關的 view 目錄下 產生一個 send_mail.rhtml 來撰寫信件裡面的內容 但是如果我們想在 Mailer View 裡面使用一些 變數 我們必須在 Mailer method 加入一些 @ 變數 class MyMail < ActionMailer::Base def send_mail( user ) # Email header info MUST be added here @recipients = '[email protected]' @from = "[email protected]" @subject = "測試標題許功蓋" # Email body substitutions go here @body["first_name"]='first name' @body["last_name"]='last name' end end 如此 Mailer 撰寫就沒啥大問題 使用 要怎麼使用他當然是在 controller 裡面使用啦 MyMail::deliver_send_mail @user 我們可以發現 我們直接使用 Mailer 而不實體化一個 Mailer Object 並且記住,我們剛剛寫了 send_mail method 但是要使用不是直接呼叫 send_mail 而是在前面加入 deliver_ 成為 deliver_send_mail 測試結果 Mailer 預設寄信的 Charset 是 UTF-8,我也測試過標題安放中文 我發現到不管是標題或是內文,都沒有中文的問題 算是很方便的機制 -- lighty RoR 是一個介紹 lighttpd , SQLite , Ruby and Rails 的 Blog http://lightyror.blogspot.com/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.230.96.54