Rails联系表单不发送电子邮件

时间:2017-05-11 05:20:20

标签: ruby-on-rails

我正在尝试在我的应用程序的页脚中设置一个简单的联系表单。 表单验证有效,但我没有收到电子邮件。

我关注了this tutorial,但更改了一些内容,因为联系表单是页脚,而不是messages/new.html.erb页面,我的应用程序中不存在该页面。

我的路线文件包含以下内容:

post 'contact-me', to: 'messages#create', as: 'create_message'

这是消息模型(没有迁移),控制器和邮件程序:

# message.rb
class Message
  include ActiveModel::Model
  attr_accessor :name, :email, :body
  validates :name, :email, :body, presence: true
end

# messages_controller.rb
class MessagesController < ApplicationController

  def create
    message_params = params.require(:message).permit(:name, :email, :body)
    @message = Message.new message_params

    if @message.valid?
      MessageMailer.contact_me(@message).deliver_now
      flash[:success] = "Message sent"
      redirect_to :back
    else
      flash[:danger] = "Message not sent. Please fill in all fields."
      redirect_to :back
    end
  end

end

# message_mailer.rb
class MessageMailer < ApplicationMailer

  def contact_me(message)
    @body = message.body

    # Note: my actual email is here, I just omitted it for this question
    mail to: "<my-email>", from: message.email
  end

end

由于联系表单位于视图的每个页面上,因此我在ApplicationController中创建了新操作:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  include SessionsHelper

  before_filter :get_message

  def get_message
    @message = Message.new
  end

end

_footer.html.erb partial呈现联系表单:

# shared/_contact_form.html.erb
<%= form_for @message, url: create_message_url do |f| %>
  <%= notice %>
  <%= render 'shared/error_messages', object: f.object %>

  <%= f.text_field :name, placeholder: 'name' %>
  <%= f.email_field :email, placeholder: 'email' %>
  <%= f.text_area :body, placeholder: 'body' %>
  <%= f.submit 'Send' %>
<% end %>

0 个答案:

没有答案