环境:
????
WIN7 X64
????
Ruby 1.9.2p290
????
Rails 3.2.3
?
在Rails 3中发邮件,与以往版本有许多不同,共有四个步骤,如下:
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
实例如下:
1、生成测试项目
????
rails new mailit
2、生成测试scaffold user并跑起来
????
rails g scaffold user name:string email:string
????
rake db:create
????
rake db:migrate
????
rails s
3、设置通用的邮件信息
????
在 config -> initializers -> setup_mail.rb
????
其中内容为:
?? ????
ActionMailer::Base.smtp_settings = {
????????????
:address???????????????????? => 'smtp.xxx.cn',
???????? ????
:port????????????????????????? => 25,
???????? ????
:domain???????????????????? =>'xxx.cn',
???????? ????
:authentication????????? => :login,
???????? ????
:user_name??????????????? => 'webmaster@xxx.cn',
???????? ????
:password????????????????? => 'secrete',
???????? ????
:enable_starttls_auto =>? true
????
???? }
??????
ActionMailer::Base.default_url_options[:host] = "localhost:3000(或者是域名)"
????
上面这句,在生产环境与开发环境中可能会不同,如果需要通过capstrano部署的话,需要修改environment环境中的development环境。
????
ActionMailer::Base.default_url_options[:host] = "localhost:3000"
4、生成邮件_控制器映射关系
????
rails g mailer user_mailer
????
生成如下文件app -> mailers ->user_mailer.rb
????
增加如下内容:
?????????
default :from => "webmaster@datasource.cn'
????? ??? def registration_confirmation(user)
????????? ? ??
mail(:to => user.email, :subject => 'Registered')
????? ??? end
?
5、建立邮件模板文件
????
Text格式
????
????
app->views->user_mailer-> registration_confirmation.text.erb
????
????
内容
????
????
Thank you for you registering!
???? HTML格式
????????? app->views->user_mailer->Registration_confirmation.html.erb
????????? 内容
????
????
????
<p><%=? @user.name %></p>
????
????
????
<p>Thank you for you registering!</p>
????
????
????
<p>Edit profile: <%=? link_to "edit_profile",edit_user_url(@user) %></p>
????
默认情况下,html的优先级高于text。
?
6、建立触发action
????
文件user_controller -> create
????
内容:
????
????
if @user.save
????
????
UserMailer.registration_confirmation(@user).deliver
?
?
参考视频:http://railscasts.com/episodes/206-action-mailer-in-rails-3?autoplay=true
?