我制作简单的联系表格而没有任何花哨的宝石,我想我已经完成了,除了生产中没有任何作品。
我在rails 4.2.0
IDE中使用Cloud9
。对于制作我使用Heroku
和邮件Mailgun
服务已在Heroku中启用。
当我尝试在开发环境中发送邮件时,我看到电子邮件是在服务器控制台中发送的,但是当我尝试在生产中执行时,它不会发送电子邮件,也不会将我重定向回到联系表单页面(在开发环境中)。也许我没有正确使用Mailgun,如果是这样,你能为邮件提供一些好的gmail
教程,所以我可以在Heroku和Digital Ocean托管平台上使用它。
messages_controller.rb
class MessagesController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(message_params)
if @message.valid?
MessageMailer.message_me(@message).deliver_now
redirect_to new_message_path, notice: "Thankyou for your message."
else
render :new
end
end
private
def message_params
params.require(:message).permit(:name, :email, :subject, :content)
end
end
message_mailer.rb
class MessageMailer < ApplicationMailer
# use your own email address here
default :to => "MYMAIL@gmail.com"
def message_me(msg)
@msg = msg
mail(from: @msg.email, subject: @msg.subject, body: @msg.content)
end
end
配置/环境/ production.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:port => ENV['587'],
:address => ENV['smtp.mailgun.org'],
:user_name => ENV['SANDBOX USERNAME GIVEN BY MAILGUN'],
:password => ENV['PASWORD'],
:domain => 'MYAPP.herokuapp.com', #eg: 'yourappname.herokuapp.com'
:authentication => :plain,
}
模型/ message.rb
class Message
include ActiveModel::Model
attr_accessor :name, :email, :subject, :content
validates :name, :email, :subject, :content, presence: true
end
视图/消息/ new.html.erb
<%= form_for @message do |f| %>
<% if @message.errors.any? %>
<div id="error_explanation">
<h2><%= "#{pluralize(@message.errors.count, "error")} prohibited this message from being sent:" %></h2>
<ul>
<% @message.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
<ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %>
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :subject %>
<%= f.text_field :subject %>
</div>
<div class="field">
<%= f.label :content %>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit 'Send', class: 'button' %>
</div>
<% end %>
答案 0 :(得分:3)
SMTP配置看起来不对。它应该从环境变量加载配置值,但您似乎试图将值放在那里:
config.action_mailer.smtp_settings = {
:port => ENV['587'],
:address => ENV['smtp.mailgun.org']
:user_name => ENV['SANDBOX USERNAME GIVEN BY MAILGUN'],
:password => ENV['PASWORD'],
:domain => 'MYAPP.herokuapp.com', #eg: 'yourappname.herokuapp.com'
:authentication => :plain,
}
这应该设置为:
config.action_mailer.smtp_settings = {
:port => 587,
:address => 'smtp.mailgun.org'
:user_name => ENV['MAILGUN_USERNAME'],
:password => ENV['MAILGUN_PASSWORD'],
:domain => 'MYAPP.herokuapp.com', #eg: 'yourappname.herokuapp.com'
:authentication => :plain,
}
然后,您需要在Cloud 9 Run面板中设置这些MAILGUN_USERNAME和MAILGUN_PASSWORD环境变量。