環境:ruby1.8.6 + rails 2.1.0 + windows
今天在整rails發送郵件,國內已經有人總結過了,寫了兩個demo,這里先來第一個,最簡單的發送郵件demo
我用的是gmail的smtp方式發送郵件,demo步驟:
1,cd進入rails工程,安裝rails的gmail支持
2,把 smtp_tls.rb ,并將其放到項目的lib目錄下
3,配置config/environment.rb文件
require 'smtp_tls' # 放到require部分
ActionMailer::Base.delivery_method = :smtp #以下放到文件的最后(end后)
ActionMailer::Base.default_charset = "UTF-8"
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "xxx.com", # 這里先不管它
:authentication => :login, # 如果不行的話,換成 :plain 試試
:user_name => "wang.fl1429", # 你的gmail賬戶名
:password => "123456", #你的gmail密碼
}
|
4,model
class Confirm < ActionMailer::Base #注意這里繼承的是ActionMailer
def send(sent_at = Time.now)
@subject = 'helloWorld' #郵件標題
@body = {'name' => '測試'}
@recipients = 'fl_1429@126.com' #收件人地址
@from = 'liverpool_long@tom.com' #發件人地址,沒起到作用
@sent_on = sent_at #發送時間
@headers = {}
end
end
|
5,controller
class ConfirmController < ApplicationController
def send_mail
Confirm.deliver_send()
render :text=> "success!"
end
end
|
6,view (views/confirm/send.rhtml) 注意必須是send.rhtml作為mail的template,不能命名為confirm.rhtml
7,發送mail
http://localhost:3000/confirm/send_mail
注意點:
1,我在開發中遇到 uninitialized constant 異常,是因為把Model名寫錯了一個字母導致的
2,model中的@from不起作用,發件人地址是environment.rb中配置的郵件地址
3,send.rhtml是發送到郵箱里的template,而非view的template
ref:
http://www.cnblogs.com/sinkzephyr/archive/2008/03/18/1111317.html
http://blog.csdn.net/long0428/archive/2007/11/14/1884586.aspx
http://www.tutorialspoint.com/ruby-on-rails-2.1/rails-send-emails.htm
http://bubble601.spaces.live.com/blog/cns!686a36348ea5ae3f!289.entry
posted on 2009-05-04 18:26
fl1429 閱讀(664)
評論(0) 編輯 收藏 所屬分類:
Rails