如何在Rails中不使用gem发送HTML表单数据至邮箱?
Hey there! Since you're new to Rails and want to keep your existing form styling intact, we can set up a custom email handler without relying on form-building gems. Here's a step-by-step guide tailored to your setup:
First, Rails requires CSRF protection to secure form submissions. Make sure your layout file (app/views/layouts/application.html.erb) has this in the <head> section:
<%= csrf_meta_tags %>
Then tweak your form tag to point to a dedicated Rails route and disable Turbo (to avoid AJAX conflicts if you're using Rails 7+):
<form method="post" name="frmContentDownload" action="<%= contact_path %>" data-turbo="false">
Your existing form fields can stay exactly as they are—no changes needed to their styling or names!
Add a POST route in config/routes.rb to map form submissions to a controller action:
post '/contact', to: 'contacts#create', as: 'contact'
Generate a lightweight controller to handle form data and trigger emails:
rails generate controller Contacts create --skip-assets --skip-helper --skip-template-engine
Open app/controllers/contacts_controller.rb and replace its content with this:
class ContactsController < ApplicationController def create # Grab form data using your existing field names contact_info = contact_params @first_name = contact_info[:FirstName1] @last_name = contact_info[:LastName1] @email = contact_info[:emailAddress] @phone = contact_info[:PhoneNumber] @title = contact_info[:Title1] @state = contact_info[:StateProvince1] @comments = contact_info[:comments] # Send the email ContactMailer.send_message( first_name: @first_name, last_name: @last_name, email: @email, phone: @phone, title: @title, state: @state, comments: @comments ).deliver_now # Redirect back with success feedback flash[:success] = "Your message was sent successfully! We'll reach out soon." redirect_to root_path rescue StandardError => e # Handle any errors gracefully flash[:error] = "Oops, something went wrong. Please try again later." redirect_to root_path end private # Strong parameters to secure form data (Rails best practice) def contact_params params.permit(:FirstName1, :LastName1, :emailAddress, :PhoneNumber, :Title1, :StateProvince1, :comments) end end
Generate a mailer to craft and send the contact email:
rails generate mailer ContactMailer send_message
Update app/mailers/contact_mailer.rb to define the email logic:
class ContactMailer < ApplicationMailer default from: 'noreply-your-app@herokuapp.com' # Use a generic app email def send_message(args) @first_name = args[:first_name] @last_name = args[:last_name] @email = args[:email] @phone = args[:phone] @title = args[:title] @state = args[:state] @comments = args[:comments] # Send the email to YOUR personal inbox mail( to: 'your-email@example.com', # Replace with your actual email subject: "New Contact Form Submission: #{@first_name} #{@last_name}", reply_to: @email # Let you reply directly to the sender ) end end
Next, create the email templates:
- For HTML emails: Open
app/views/contact_mailer/send_message.html.erband add:
<h1>New Contact Form Submission</h1> <p><strong>Full Name:</strong> <%= @first_name %> <%= @last_name %></p> <p><strong>Email:</strong> <%= @email %></p> <p><strong>Phone:</strong> <%= @phone %></p> <p><strong>Title:</strong> <%= @title %></p> <p><strong>Country/State:</strong> <%= @state %></p> <p><strong>Comments:</strong> <%= @comments %></p>
- For plain-text fallback: Create
app/views/contact_mailer/send_message.text.erbwith:
New Contact Form Submission Full Name: <%= @first_name %> <%= @last_name %> Email: <%= @email %> Phone: <%= @phone %> Title: <%= @title %> Country/State: <%= @state %> Comments: <%= @comments %>
Development Environment
Use the letter_opener gem to preview emails locally without sending them:
- Add to your Gemfile:
gem 'letter_opener', group: :development
- Run
bundle install - Update
config/environments/development.rb:
config.action_mailer.delivery_method = :letter_opener config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
Now when you submit the form locally, a browser tab will open with the email preview.
Production (Heroku)
Use SendGrid's free tier to send emails from Heroku:
- Add the SendGrid add-on via Heroku CLI:
heroku addons:create sendgrid:starter
- Update
config/environments/production.rb:
config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'smtp.sendgrid.net', port: 587, domain: 'herokuapp.com', user_name: ENV['SENDGRID_USERNAME'], password: ENV['SENDGRID_PASSWORD'], authentication: :plain, enable_starttls_auto: true } config.action_mailer.default_url_options = { host: 'gastromend.herokuapp.com' }
Heroku auto-sets the SENDGRID_USERNAME and SENDGRID_PASSWORD environment variables, so no manual input needed.
To let users know their submission worked, add flash messages to your layout (application.html.erb):
<% if flash[:success] %> <div class="alert alert-success"><%= flash[:success] %></div> <% end %> <% if flash[:error] %> <div class="alert alert-danger"><%= flash[:error] %></div> <% end %>
- Local: Start your server with
rails s, submit the form, and check the letter_opener preview. - Production: Push your code to Heroku with
git push heroku main, then test the form on your live app.
内容的提问来源于stack exchange,提问作者weng tee

