Rails Net::OpenTimeout Mailer Namecheap Heroku Не удалось отправить почтовую программу с ошибкой 500

Я попытался отправить электронное письмо для сброса пароля через домен namecheap. Я просмотрел каждое решение, предлагаемое в StackOverflow, и не смог найти жизнеспособного решения. Дайте мне знать, если мне не хватает какой-либо информации ниже. Мое приложение Rails — это только API.

Он работал через соединение gmail/smtp, и когда я переключил его на smtp namecheap/privateemail, он сработал один раз. После того, как он заработал локально, я загрузил код на героку, и вот тогда он начал давать сбой.

# config/environments/development.rb
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: '[email protected]'}

config.action_mailer.default_url_options = { :host => '587'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {

address:              'mail.privatemail.com',
port:                 587,
domain:               'domainname.com',
user_name:            ENV['EMAIL'],
password:             ENV['EMAIL_PW'],
authentication:       :plain,
enable_starttls_auto: true,
openssl_verify_mode:  'none',
ssl:                  true
}

Производство:

config.cache_classes = true
  config.action_mailer.delivery_method = :sendmail
  config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_options = {from: '[email protected]'}
  config.action_mailer.delivery_method = :smtp

  config.action_mailer.smtp_settings = {
  address:              'mail.privatemail.com',
  port:                 587,
  domain:               'domainname.com',
  user_name:            ENV['EMAIL'],
  password:             ENV['EMAIL_PW'],
  authentication:       :plain,
  enable_starttls_auto: true,
  openssl_verify_mode:  'none'
  }

Класс NotifierMailer

class NotifierMailer < ApplicationMailer
  default_url_options[:host] = ENV['BACKEND_URL']
  default from: '[email protected]'


  def create
    admin = Admin.find_by(email: params[:email])
    admin.generate_password_reset_token!
    Notifier.password_reset(admin).deliver
  end

  def password_reset(admin)
    @admin = admin
    @url = "#{ENV['BACKEND_URL']}/password/reset?token=#{@admin.reset_password_token}&email=#{@admin.email}"
    mail(to: "#{@admin.first_name} #{@admin.last_name} <#{@admin.email}>",
         subject: "Ion Portal - Password Reset")
  end

end

Контроллер паролей

class PasswordController < ApplicationController
  protect_from_forgery with: :null_session
  # include ActionController::RequestForgeryProtection
  # protect_from_forgery with: :exception, unless: -> { request.format.json? }


  def forgot
    puts params
   if params[:email].blank? # check if email is present
    render json: {
       error: "Email not present"
     }
   end

   admin = Admin.find_by(email: params[:email]) # if present find admin by email
    if admin.present?
      admin.generate_password_token! #generate pass token
      NotifierMailer.password_reset(admin).deliver_now
      render json: { status: 'ok' }
    else
      render json: { error: ["Email address not found. Please check and try again."]}, status: :not_found
    end
  end

 def reset
   token = params[:token].to_s
   if params[:email].blank?
     return render json: {error: "Token not present"}
   end

   admin = Admin.find_by(reset_password_token: token)
   if admin.present? && admin.password_token_valid?
     if admin.reset_password!(params[:password])
       redirect_to "#{ENV['ION_URL']}"
     else
       render json: {error: admin.errors.full_messages}, status: :unprocessable_entity
     end
   else
     render json: { error:  ["Link not valid or expired. Try generating a new link."]}, status: :not_found
   end
 end

 def update
   if !params[:password].present?
    render json: {error: 'Password not present'}, status: :unprocessable_entity
    return
   end

   if current_user.reset_password(params[:password])
     render json: {status: 'ok'}, status: :ok
   else
     render json: {errors: current_user.errors.full_messages}, status: :unprocessable_entity
   end
 end

 def successful_reset
   render success_path
 end

end

person Roger Perez    schedule 10.04.2019    source источник


Ответы (2)


Эти настройки мне подошли. Оказалось, что я также оставил настройки для MailCatcher, это была моя первоначальная проблема. Также дважды проверьте, совпадают ли настройки домена и адреса сервера, что в процессе разработки означает установку домена на «localhost: 3000». Удачи!

config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address              => 'mail.privateemail.com',
:port                 => 587,
:domain               => 'localhost:3000',
:user_name            => '[email protected]',
:password             => 'xxxxxxxxxxxxxxx',
:authentication       => :plain,
:enable_starttls_auto => true,
}
person Pete Kreppein    schedule 12.04.2019

После 24 часов проб и ошибок мне пришлось удалить пару строк кода, чтобы заставить его работать.

 config.action_mailer.smtp_settings = {
# For Gmail
      # :address              => "smtp.gmail.com",
      # :port                 => "587",
      # :domain               => "gmail.com",
      # :user_name            => "[email protected]",
      # :password             => "pasword!",
      # :authentication       => "plain",
      # :enable_starttls_auto => true

# For Namecheap

      :enable_starttls_auto => true,  #this is the important stuff!
      :address        => 'smtp.privateemail.com',
      :port           => 587,
      :domain         => 'privateemail.com',
      :authentication => :plain,
      :user_name      => '[email protected]',
      :password       => 'password!'
    }

I removed the following: 

    enable_starttls_auto: true,
      openss

    l_verify_mode:  'none'
person Roger Perez    schedule 16.04.2019