2015-09-30 1 views
0

Кажется, что такая простая вещь, я не хочу использовать программу или других пользователей, это мой личный сайт, на котором я показываю свою работу. Все, что я хочу сделать, это связаться со мной по электронной почте, чтобы я мог получать сообщения от людей, которые посещают мой сайт. Весь учебник, с которым я столкнулся, отправляет электронное письмо пользователю.Как отправить контакт со мной по электронной почте с моего сайта rails

Когда я пытаюсь создать письмо. Это то, что я получаю:

SMTP-AUTH запрошено, но отсутствует имя

@contact = Contact.new(params[:contact]) 
@contact.request = request 
if @contact.deliver 
    flash.now[:notice] = 'Thank you, I will contact you soon.' 
    redirect_to root_path 
else 

пользователя это мой контактный контроллер:

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

    def create 
    @contact = Contact.new(params[:contact]) 
    @contact.request = request 
    if @contact.valid? 
     ContactMe.contact_email(@contact).deliver 
     redirect_to root_path 
     flash[:notice] = "Message sent from {@contact.name}" 
    else  
     render :new 
     flash.now[:error] = 'Could not send message as is. Please check email and phone fields.' 
    end 
    end 
end 

контакт модель:

class Contact < MailForm::Base 
    attribute :name,  :validate => true 
    attribute :email,  :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i 
    attribute :message 


    # Declare the e-mail headers. It accepts anything the mail method 
    # in ActionMailer accepts. 
    def headers 
    { 
     :subject => "Contact", 
     :to => "[email protected]", 
     :from => %("#{name}" <#{email}>) 
    } 
    end 
end 

class ContactMe < ApplicationMailer 

    def contact_email(contact) 
    @contact = contact 
    mail(to: '[email protected]', from: @contact.email, :subject => "Website Contact") 
    end 
end 

производство. rb:

Rails.application.configure do 
    # Settings specified here will take precedence over those in config/application.rb. 

    # Code is not reloaded between requests. 
    config.cache_classes = true 

    # Eager load code on boot. This eager loads most of Rails and 
    # your application in memory, allowing both threaded web servers 
    # and those relying on copy on write to perform better. 
    # Rake tasks automatically ignore this option for performance. 
    config.eager_load = true 

    # Full error reports are disabled and caching is turned on. 
    config.consider_all_requests_local  = true 
    config.action_controller.perform_caching = true 

    # Enable Rack::Cache to put a simple HTTP cache in front of your application 
    # Add `rack-cache` to your Gemfile before enabling this. 
    # For large-scale production use, consider using a caching reverse proxy like 
    # NGINX, varnish or squid. 
    # config.action_dispatch.rack_cache = true 

    # Disable serving static files from the `/public` folder by default since 
    # Apache or NGINX already handles this. 
    config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? 

    # Compress JavaScripts and CSS. 
    config.assets.js_compressor = :uglifier 
    # config.assets.css_compressor = :sass 
    config.action_mailer.perform_deliveries = true 
    config.action_mailer.raise_delivery_errors = true 
    config.action_mailer.delivery_method = :smtp 
    config.action_mailer.default_url_options = { :host => 'nicolasdev.herokuapp.com' } 
    config.action_mailer.smtp_settings = { 
    :address    => "smtp.gmail.com", 
    :port     => 587, 
    :domain    => 'gmail.com', 
    :enable_starttls_auto => true, 
    :user_name   => ENV["GMAIL_USERNAME"], 
    :password    => ENV["GMAIL_PASSWORD"], 
    :authentication  => "plain" 

    } 

    # Do not fallback to assets pipeline if a precompiled asset is missed. 
    config.assets.compile = true 
    config.assets.precompile = ['*.js', '*.css', '*.jpg', '*.png', '*.gif', '*.ico'] 

    # Asset digests allow you to set far-future HTTP expiration dates on all assets, 
    # yet still be able to expire them through the digest params. 
    config.assets.digest = true 

    # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 

    # Specifies the header that your server uses for sending files. 
    # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 
    # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 

    # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 
    # config.force_ssl = true 

    # Use the lowest log level to ensure availability of diagnostic information 
    # when problems arise. 
    config.log_level = :debug 

    # Prepend all log lines with the following tags. 
    # config.log_tags = [ :subdomain, :uuid ] 

    # Use a different logger for distributed setups. 
    # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 

    # Use a different cache store in production. 
    # config.cache_store = :mem_cache_store 

    # Enable serving of images, stylesheets, and JavaScripts from an asset server. 
    # config.action_controller.asset_host = 'http://assets.example.com' 

    # Ignore bad email addresses and do not raise email delivery errors. 
    # Set this to true and configure the email server for immediate delivery to raise delivery errors. 
    # config.action_mailer.raise_delivery_errors = false 

    # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 
    # the I18n.default_locale when a translation cannot be found). 
    config.i18n.fallbacks = true 

    # Send deprecation notices to registered listeners. 
    config.active_support.deprecation = :notify 

    # Use default logging formatter so that PID and timestamp are not suppressed. 
    config.log_formatter = ::Logger::Formatter.new 

    # Do not dump schema after migrations. 
    config.active_record.dump_schema_after_migration = false 
end 

application.yml:

GMAIL_USERNAME: '[email protected]' 
GMAIL_PASSWORD: 'literallymyemailpassword' 

Я, вероятно, делает много ошибок, но, пожалуйста, помилуй меня. Я был на этом некоторое время, скрываясь от других сообщений и учебных пособий безрезультатно.

+0

Существует блок электронной почты за пределами Rails, который необходимо установить и настроить, прежде чем вы сможете отправлять почту. Приложения Heroku могут использовать Sendgrid очень легко, но вы должны включить его. Вы добавили Sendgrid в свое приложение Heroku? – Elvn

+0

Я не знал об этом. Я сделаю некоторые исследования. Это не обсуждалось ни в одном из учебных пособий. –

+0

. Здесь можно найти хорошее место: https://devcenter.heroku.com/articles/sendgrid – Elvn

ответ

0

Благодарим вас за советы по sendgrid, это было, вероятно, следующее, что я собирался сбить голову с головы. Спасибо, что спасли мне головную боль. Моя проблема была глубже, чем это. Кажется, что один из моих драгоценных камней зависел от sql3, который вызывал его не обновлять мой контроллер. Я никогда не замечал, что я не подталкивал свои изменения (ох!). Я действительно заметил это после того, как увидел свой собственный пост и увидел разницу в журнале ошибок и контроллер в моем github. Не знаю, насколько полезен этот вопрос для сообщества, но кто знает ... Спасибо за помощь.