Ask A Question

Notifications

You’re not receiving notifications from this thread.

Rails How to link an email form with Sendgrid?

Omar Khedr asked in Rails

I was able to create a contact form that when a user clicks submit - its send an email (which i get in my yahoo inbox).

I would like to now have that email be sent via sendgrid so that I can analyze analytics. I looked at the Gorails Sendgrid course and was able to send an email via sendgrid through his example but I don't know how to apply that now to my contact form. I have listed my code below, any help would be amazing. Thank you so much!

new.html.erb (Contact Form which sends an email regularly when a user clicks submit)

<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 (Within my config > initializers folder)

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
}

development.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
}

Mailers Folder (I only have two files Notification and application none deal with my Contacts Form)

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,110+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.