Rails通过actionmailer和activemodel,SMTPAuthenticationError给自己发送电子邮件

时间:2017-01-22 19:59:02

标签: ruby-on-rails actionmailer activemodel

我正在尝试生成表单,以便访问者可以将电子邮件发送到固定地址,而不会使数据库混乱。当我测试表单时,rails返回此错误...

In [30]: tmp.index.name = 'WORD'
In [36]: tmp = tmp.rename(columns={0: 'TEXT', 1: 'FREQ'})
In [37]: print(tmp)

      TEXT FREQ
WORD
alfa   001    2
beta   001    3
gamma  001    2
alfa   002    6
beta   002    4
omega  002    7

似乎答案是允许访问不太安全的应用程序的Gmail。如何在不降低安全性的情况下保留功能?

控制器/ contacts_controller.rb

Net::SMTPAuthenticationError in ContactsController#create 

寄件人/ contact_mailer.rb

class ContactsController < ApplicationController
  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact])
    if @contact.valid?
      ContactMailer.contact_submit(@contact).deliver
      flash[:notice] = "Thank you for your email, I'll respond shortly"
      redirect_to new_contact_path
    else
      render :new
    end
  end
end

模型/ contact.rb

class ContactMailer < ActionMailer::Base
  default to: "#{ENV['GMAIL_USERNAME']}@gmail.com"

  def contact_submit(msg)
    @msg = msg
    mail(from: @msg.email, name: @msg.name, message: @msg.message)
  end
end

配置/环境/ development.rb

class Contact
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :message

  validates_format_of :email, :with => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  validates_presence_of :message
  validates_presence_of :name

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

配置/环境/ production.rb

  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true
  config.action_mailer.default :charset => 'utf-8'
  config.action_mailer.smtp_settings = {
    address: 'smtp.gmail.com',
    port: 587,
    domain: 'localhost:3000',
    user_name: ENV['GMAIL_USERNAME'],
    password: ENV['GMAIL_PASSWORD'],
    authentication: 'plain',
    enable_starttls_auto: true
  }

1 个答案:

答案 0 :(得分:1)

您是否配置了SMTP Settings in ActiveMailer

此外,当您使用google smtp服务器中的随机电子邮件地址时,很可能会遇到垃圾邮件问题。

更好的想法是使用固定的发件人地址(例如您自己的地址)并将原始地址放在文本中。这就是大多数电子邮件形式的工作原理。

修改:根据another StackOverflow answer,您需要在电子邮件设置中启用安全性较低的应用。