在Rails中联系Form Mailer 4

时间:2013-12-25 06:33:01

标签: ruby-on-rails ruby ruby-on-rails-4 actionmailer contact-form

我正在尝试在Rails 4中构建一个联系表单,其中表单采用名称,电子邮件和正文,并将其发送到我的电子邮件地址。点击“提交”后,该应用会正确地重定向回联系人页面,但似乎没有电子邮件被发送。

的routes.rb

match '/send_mail', to: 'contact#send_mail', via: 'post'

contact_email.html.erb

<!DOCTYPE html>
<html>
    <head>
        <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
        <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>You have received the following email from <%= "#{ @name } (#{ @email }):" %></p>
        <p><%= @body %></p>
    </body>
</html>

contact_controller.rb

def send_mail
    name = params[:name]
    email = params[:email]
    body = params[:comments]
    ContactMailer.contact_email(name, email, body).deliver
    redirect_to contact_path, notice: 'Message sent'
end

contact_mailer.rb

class ContactMailer < ActionMailer::Base
    default to: # my email address

    def contact_email(name, email, body)
        @name = name
        @email = email
        @body = body`enter code here`

        mail(from: email, subject: 'Contact Request')
    end
end

contact.html.erb

<div class="container-content">
    <div class="container">
        <%= form_tag(send_mail_path) do %>
            <div class="form-group">
                <%= label_tag 'name', 'Name' %>
                <%= text_field_tag 'name', nil, class: 'form-control', placeholder: 'Your Name' %>
            </div>
           <div class="form-group">
               <%= label_tag 'email', 'Email' %>
               <%= email_field_tag 'email', nil, class: 'form-control', placeholder: 'Your Email Address' %>
           </div>
           <div class="form-group">
               <%= label_tag 'comments', 'Comments' %>
               <%= text_area_tag 'comments', nil, class: 'form-control', rows: 4, placeholder: 'Comments...' %>
           </div>
           <%= submit_tag nil, class: 'btn btn-default btn-about pull-right' %>
       <% end %>
  </div>
</div>

application.rb中

config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true

1 个答案:

答案 0 :(得分:14)

事实证明我没有使用外部SMTP服务配置我的Heroku应用程序(因为我之前从未做过任何关于电子邮件的事情,我不知道这样做)。由于我对MailChimp比较熟悉,特别是因为他们的Mandrill服务有免费等级(我正在为学生组织构建这个应用程序),我很容易将Mandrill添加到我的Heroku应用程序中,并在应用程序中包含以下设置。 RB

ActionMailer::Base.smtp_settings = {
    address: 'smtp.mandrillapp.com',
    port: 587,
    user_name: ENV['MANDRILL_USERNAME'],
    password: ENV['MANDRILL_APIKEY']
}

通过附加组件自动设置ENV变量。