顯示具有 actionmailer 標籤的文章。 顯示所有文章
顯示具有 actionmailer 標籤的文章。 顯示所有文章

2/22/2007

使用 GMail SMTP 來幫你寄信

ActionMailer 自從上次介紹了 sendmail 寄信後,好像一直沒介紹如何用 smtp 來寄信。不過由於這個部分聖經本以及 Rails Wiki都介紹的非常詳細,我就請大家多看看書好了。這裡直接介紹如何使用 Gmail 的 SMTP Server 幫你寄信。

Anatol Pomozov 感嘆 Ruby 的標準處理 SMTP的 Lib Net:SMTP 一直不支援 TLS,於是他決定自己來寫。他寫了一個 tls 的 lib 叫做 smtp_tls.rb 。讓我們可以直接使用支援 TLS 的 SMTP Server 來幫我們寄信。

code 內容因為 license 不明,請大家直接去原作者出處來看。使用方是就是將這段 code 放入任何一個 Rails 讀的到的地方。然後在 config/enviroment.rb 裡面加入
require ‘smtp_tls’

最後在 config/enviroments/xxxxx.rb 裡面寫相關 Gmail 設定
ActionMailer::Base.server_settings = {
:address => "smtp.gmail.com",
:port => "587",
:domain => "localhost.localdomain",
:authentication => :plain,
:user_name => "你的Gmail account",
:password => "你的Gmail Password"
}


如此即可。

9/15/2006

初探 ActionMailer : 使用 sendmail 寄信

Action Mailer 是 Ruby on Rails 上面收發信的機制
不過因為收信實在牽涉到太多東西
我們先不予以探索,只論發信的機制

就算是寄信,也有很多方式
可以用 SMTP Server 來寄
但是也要設定很多東西
身為 Rails Programmer ,而非網管
我們先使用最最最簡單的 sendmail 來寄信

測試Sendmail

要用寄信前,請先在命令列上打
sendmail abc@example.com
等到他出現下一行
就可以亂打一些內容
然後按下 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 = 'thegiive@gmail.com'
@from = "accounts@mywebsite.com"
@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 = 'thegiive@gmail.com'
@from = "accounts@mywebsite.com"
@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,我也測試過標題安放中文
我發現到不管是標題或是內文,都沒有中文的問題
算是很方便的機制