ActionMailer不会发送邮件?

Joh*_*ohn 4 email ruby-on-rails actionmailer

我正在尝试在我的开发环境中设置一个简单的contact_us页面,用户可以使用我创建的表单发送查询.我有ActiveMailer和Contact模型/控制器/视图都设置但它似乎没有正常工作.有任何想法吗?我的日志似乎显示正在发送的邮件.

的ActionMailer

class ContactConfirmation < ActionMailer::Base
  default from: "from@example.com"

  def receipt(contact)
    @contact = contact

    mail to: 'myname@example.com',
      subject: contact.subject
  end
end
Run Code Online (Sandbox Code Playgroud)

收据

<%= @contact.first_name %> <%= @contact.last_name %>

Writes:

<%= @contact.description %>
Run Code Online (Sandbox Code Playgroud)

ContactsController

class ContactsController < ApplicationController

  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(contact_params)
    if @contact.submit_contact_info
      redirect_to users_path, notice: 'Submission successful. Somebody will get back to you shortly.'
    else
      render :new
    end
  end

  protected

  def contact_params
    params.require(:contact).permit(:first_name, :last_name, :email, :subject, :description)
  end
end
Run Code Online (Sandbox Code Playgroud)

联系型号

class Contact < ActiveRecord::Base
  validates_presence_of :email
  validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i }
  validates_presence_of :subject
  validates_presence_of :description
  validates_presence_of :first_name
  validates_presence_of :last_name

  def submit_contact_info
    if save
      ContactConfirmation.receipt(self).deliver
      return true
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

联系人在contacts/new.html.erb文件中呈现的表单

<%= simple_form_for @contact do |f| %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.input :email %>
  <%= f.input :subject %>
  <%= f.input :description, as: :text %>
  <%= f.submit 'Submit Contact Form' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

在Initializers文件夹中,我有一个smtp.rb文件:

if Rails.env.development?
  ActionMailer::Base.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    address: "localhost",
    port: 1025
  }
end
Run Code Online (Sandbox Code Playgroud)

更改我的配置后,现在出现以下错误ContactConfirmation.receipt(self).deliver:

在ContactsController中的Errno :: ECONNREFUSED#create连接被拒绝 - 连接(2)

def submit_contact_info
    if save
      ContactConfirmation.receipt(self).deliver
      return true
    end
  end
Run Code Online (Sandbox Code Playgroud)

zrl*_*3dx 5

所以让我们从头开始:

在开发模式下,默认情况下不会传递邮件,也不会提高传递错误,这就是您没有错误和没有电子邮件的原因.要更改此项,请将以下内容添加到配置并重新启动服务器:

配置/环境/ development.rb

config.action_mailer.raise_delivery_errors = true 
config.action_mailer.perform_deliveries = true
Run Code Online (Sandbox Code Playgroud)

现在您应该收到一些错误或收到电子邮件.正如您在评论中写的那样,您收到了Connection refused错误,因此这意味着您的邮件程序守护程序未运行.你正在使用mailcatcher(因此1025端口)所以在安装之后你应该简单地运行它mailcatcher.现在你应该没有错误,你应该能够在浏览后看到你的电子邮件localhost:1080.