Rails 如何将电子邮件表单与 Sendgrid 链接?



我能够创建一个联系表单,当用户单击提交时 - 它会发送电子邮件,并在收件箱中收到。我希望通过sendgrid发送该电子邮件,以便我可以分析分析。我查看了Gorails Sendgrid课程,并能够通过sendgrid发送电子邮件,但我不知道如何将其应用于我的联系表格。我在下面列出了我的代码,任何帮助都会很棒。非常感谢!

new.html.erb(当用户点击提交时定期发送电子邮件的联系表(

<div align="center">
<h3>Send A message to Us</h3>
<%= form_for @contact do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name, :required => true %>
</div>
<div class="field">
<%= f.label :email %><br>
<%= f.email_field :email, :required => true %>
</div>
<div class="field">
<%= f.label :message %><br>
<%= f.text_area :message, :as => :text, :required => true %>    
</div>
<div class="actions">
<%= f.submit "Send Message", :class => "btn btn-primary btn-md"%>
</div>
<% end %>
</div>

contacts_controller.rb

class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(contact_params) 
@contact.request = request
if @contact.deliver
flash.now[:notice] = 'Thank you for your message. We will contact you soon!'
else
flash.now[:error] = 'Cannot send message.'
render :new
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :message)
end
end

Sendgrid.rb (在我的配置>初始化程序文件夹中(

ActionMailer::Base.smtp_settings = {
:user_name => 'apikey',
:password => Rails.application.secrets.sendgrid_api_key,
:domain => 'tango.co',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}

发展.rb

config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:user_name => 'apikey',
:password => Rails.application.secrets.sendgrid_api_key,
:domain => 'tango.co',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}

邮件文件夹(我只有两个文件通知和应用程序没有处理我的联系人表单(

我弄清楚了我错过了什么。我需要为联系人生成邮件。完成此操作并在我的 contacts_controller.rb 中添加一行后,我能够通过 sendgrid 毫无问题地发送电子邮件:)

class ContactsController < ApplicationController  
def new
@contact = Contact.new
end
def create
@contact = Contact.new(contact_params) 
@contact.request = request
if @contact.save
ContactMailer.new_request(@contact.id).deliver_later
end
if @contact.deliver
flash.now[:notice] = 'Thank you for your message. We will contact you soon!'
else
flash.now[:error] = 'Cannot send message.'
render :new
end
end
private
def contact_params 
params.require(:contact).permit(:name, :email, :message)
end
end

联系人邮件

class ContactMailer < ApplicationMailer 
def new_request
end
end

最新更新