Rails 5 mailform不发送邮件

时间:2017-01-08 03:25:19

标签: ruby-on-rails heroku ruby-on-rails-5 mail-form

我正在尝试使用mailform gem在我的rails 5 app中建立一个联系我们页面。我按照YouTube视频说明了这个过程:https://www.youtube.com/watch?v=QIoORYeBdhs

但是,我无法在开发或生产模式下获得实际发送的电子邮件,而且我不确定为什么。任何帮助将非常感激!

这就是我所拥有的:

Welcome.rb:

class Welcome < MailForm::Base
    attribute :name, :validate => true
    attribute :email, :validate => /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
    attribute :message, :validate => true
    attribute :nickname, :captcha => true

    def headers 
        {
            :subject => "Contact from About Site",
            :to => "my_email@gmail.com", 
            :from => %("#{name}" <#{email}>)
        }
    end
end

welcome_controller:

class WelcomeController < ApplicationController
  def index
    @welcome = Welcome.new
  end

  def create
    @welcome = Welcome.new(params[:welcome])
    @welcome.request = request
    if @welcome.deliver
        flash.now[:error] = nil
    else
        flash.now[:error] = 'Cannot send message.'
        render :index
    end
  end
end

表单本身:(index.html.erb)

<section id="contact">
    <div class="container">
        <%= form_for welcome_index_path do |f| %>
            <%= f.label :name %>
            <%= f.text_field :name, required: true %>
            <br>
            <%= f.label :email %>
            <%= f.email_field :email, required: true %>
            <br>
            <%= f.label :message %>
            <%= f.text_area :message, as: :text %>
            <div class="hidden">
                <%= f.label :nickname %>
                <%= f.text_field :nickname, hint: "Leave this field blank" %>
            </div>
            <br>
            <%= f.submit 'Send Message', class: "btn btn-primary btn-large" %>
        <% end %>
    </div>
</section>

现在我的配置文件:

production.rb,使用带有sendgrid的heroku:

# email
config.action_mailer.default_url_options = {host: 'https://my_heroku_app.herokuapp.com'}
  config.action_mailer.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    :address => 'smtp.sendgrid.net',
    :port => '587',
    :authentication => :plain, 
    :user_name => ENV["SENDGRID_USERNAME"],
    :password => ENV["SENDGRID_PASSWORD"],
    :domain => 'heroku.com',
    :enable_starttls_auto => true 
  }

development.rb,使用gem mailcatcher:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default :charset => "utf-8"
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {:address => "localhost", :port => 1025}

1 个答案:

答案 0 :(得分:0)

我自己的回答 看起来实际上上面的代码运行得很好,并且sendgrid启动只是一个延迟。花了大约两天时间,我不知道为什么,但现在它没有对代码进行真正的修改就能正常工作