Create Rails app
rails new my_app cd my_appCreate mailer
rails g mailer notifierCreate Support Resource
rails g resource supportRemove Support's migration (we don't use database)
rm db/migrate/20100323085113_create_supports.rbSending email via Gmail
# config/initializers/mailer.rb
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:enable_starttls_auto => true,
:address => 'smtp.gmail.com',
:port => 587,
:domain => "yourdomain.com",
:user_name => '[email protected]',
:password => 'yourpassword',
:authentication => 'plain'
}
# app/mailer/notifier.rb
class Notifier < ActionMailer::Base
def support_notification(sender)
@sender = sender
mail(:to => "[email protected]",
:from => sender.email,
:subject => "New #{sender.support_type}")
end
end
# app/views/notifier/support_notification.html.erb hello world! <%= @sender.content %>
# config/routes.rb resources :supports, :only => [:new, :create]
# app/controller/supports_controller.rb
class SupportsController < ApplicationController
def new
# id is required to deal with form
@support = Support.new(:id => 1)
end
def create
@support = Support.new(params[:support])
if @support.save
redirect_to('/', :notice => "Support was successfully sent.")
else
flash[:alert] = "You must fill all fields."
render 'new'
end
end
end
# app/models/support.rb
class Support
include ActiveModel::Validations
validates_presence_of :email, :sender_name, :support_type, :content
# to deal with form, you must have an id attribute
attr_accessor :id, :email, :sender_name, :support_type, :content
def initialize(attributes = {})
attributes.each do |key, value|
self.send("#{key}=", value)
end
@attributes = attributes
end
def read_attribute_for_validation(key)
@attributes[key]
end
def to_key
end
def save
if self.valid?
Notifier.support_notification(self).deliver!
return true
end
return false
end
end
# app/views/supports/new.html.erbContact Us
<%= render 'form' %>
# app/views/supports/_form.html.erb
<% form_for @support, :url => { :action => "create" }, :html => { :method => :post } do |f| %>
<p>
<%= f.label "Name" %>
</p>
<p>
<%= f.text_field :sender_name %>
</p>
<p>
<%= f.label "Email" %>
</p>
<p>
<%= f.text_field :email %>
</p>
<p>
<%= f.label "Type" %>
</p>
<p>
<%= f.select :support_type, options_for_select(["Bug", "Ask", "Idea"]) %>
</p>
<p>
<%= f.label "Details" %>
</p>
<p>
<%= f.text_area :content %>
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
Raise Exception When Mailer Can't Send the Email (Development mode)# config/environments/development.rb # ... config.action_mailer.raise_delivery_errors = true # ...done! To try this code, open http://localhost:3000/supports/new or try the code via Rails console.
support = Support.new(:email => "[email protected]", :sender_name => "my name", :support_type => "bug", :content => "this is my support") support.save
38 comments: