使用Rails来发送Email. Rails Mailer概貌
1. script/generate mailer postoffice
2. 对你的邮件程序生成一个方法(models/postoffice.rb)
3.生成你自己的邮件template, 使用welcome.text.html.erb 和welcome.text.plain.erb (views/postoffice)
4. 发送信息
5.如果你进行本地php?name=%B2%E2%CA%D4" οnclick="tagshow(event)" class="t_tag">测试,确定postfix在运行。
打开你的终端:
add3-imac: jon$ rails mailer_example
-- output truncated --
add3-imac: jon$ cd mailer_example/
add3-imac:mailer_example jon$ script/generate mailer postoffice
exists app/models/
create app/views/postoffice
exists test/unit/
create test/fixtures/postoffice
create app/models/postoffice.rb
create test/unit/postoffice_test.rb
现在我们为邮件程序生成一个方法:
class Postoffice < ActionMailer::Base
# located in models/postoffice.rb
# make note of the headers, content type, and time sent
# these help prevent your email from being flagged as spam
def welcome(name, email)
@recipients = "jon@addthree.com"
@from = params[:contact][:email]
headers "Reply-to" => "#{email}"
@subject = "Welcome to Add Three"
@sent_on = Time.now
@content_type = "text/html"
body[:name] = name
body[:email] = email
end
end
现在我们已经产生了我们的方法,需要改变template:
# located in views/postoffice
# we can access the variables we declared in models/postoffice.rb
# body[:name] = name is accessed by @name
# body[:email] = email is accessedby @email
# welcome.text.html.erb
# note the HTML
<p>Welcome to AddThree <i><%= @name %></i>. </p>
<p>The address we have on file for you is <b><%= @email %></b>, please let us know if this is incorrect.</p>
# welcome.text.plain.erb
Welcome to AddThree <%= @name %>. The address we have on file for you is <%= @email %>, please let us know if this is incorrect.
现在我们的邮件和template都已经准备好了,让我们发送邮件吧:
class Registration < ApplicationController
# controllers/registration_controller.rb
# assume the Registration controller already existed
# assume @user.name and @user.email have been declared
def send_welcome_email
# triggered via:
# http://localhost:3000/registration/send_welcome_email
# note the deliver_ prefix, this is IMPORTANT
Postoffice.deliver_welcome(@user.name, @user.email)
# optional, but I like to keep people informed
flash[:notice] = "You've successfuly registered. Please check your email for a confirmation!"
# render the default action
render :action => 'index'
end
end
如果您进行本地测试,确定postfix在运行
add3-imac:mailer_example jon$ sudo postfix start
Password:
postfix/postfix-script: starting the Postfix mail system
Sorry, no time to modify the codes to text style
thanks to http://www.jonathansng.com/ruby- ... end-email-tutorial/
by jonathan, and thanks to jonathan
转载 使用Rails来发送Email. Rails Mailer概貌
最新推荐文章于 2017-06-30 11:45:10 发布