2017-01-22 80 views
0

我想要生成一個表單,以便訪問者可以發送電子郵件到一個固定的地址而不會混亂數據庫。當我測試的形式,軌道返回該錯誤......Rails通過actionmailer和activemodel給我發電子郵件,SMTPAuthenticationError

Net::SMTPAuthenticationError in ContactsController#create 

看來,答案是允許訪問Gmail的安全性較低的應用程序。我如何在不降低安全性的情況下保留功能?

控制器/ contacts_controller.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_mailer.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 

模型/ contact.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 

配置/環境/ development.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 
    } 

配置/環境/ production.rb

config.action_mailer.default_url_options = { host: ENV['WEBSITE'] } 
    config.action_mailer.delivery_method = :smtp 
    config.action_mailer.smtp_settings = { 
    address: 'smtp.gmail.com', 
    port: 587, 
    domain: ENV['WEBSITE'], 
    user_name: ENV['GMAIL_USERNAME'], 
    password: ENV['GMAIL_PASSWORD'], 
    authentication: 'plain', 
    enable_starttls_auto: true 
    } 

回答

1

你配置SMTP Settings in ActiveMailer

此外,當您僅使用谷歌smtp服務器的隨機電子郵件地址時,您很可能會遇到垃圾郵件問題。

更好的主意是使用固定的發件人地址(例如您自己的地址)並將原始地址放在文本中。這就是大多數電子郵件表單的工作原理

編輯:根據another StackOverflow answer,您需要在您的電子郵件設置中啓用安全性較低的應用程序。

+0

我記得當我試圖郵寄到我自己的Gmail地址時遇到類似的問題。 IIRC與G安全設置有關,是的。我使用Mailtrap等免費郵件服務解決了這個問題。這對你來說是一種選擇嗎? Mailtrap捕獲您從應用發送的所有郵件。 – Mauddev

+0

我配置了stmp設置,代碼在上面列出。我還使用了一個固定的電子郵件地址,它位於我的env文件中,並在上面的代碼中作爲ENV常量引用。 –

+0

那麼你是否已經在GMail帳戶中配置了你的設置?到此SO回答:http://stackoverflow.com/questions/25872389/rails-4-how-to-correctly-configure-smtp-settings-gmail#answer-32019587 – leifg

相關問題