如何在Ruby Rails中实现点击提交发送邮件的代码?
实现点击按钮发送邮件的Rails步骤
1. 配置邮件环境(开发环境示例)
打开 config/environments/development.rb,添加或修改邮件配置:
config.action_mailer.delivery_method = :letter_opener config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
letter_opener 可以在浏览器直接预览邮件,无需实际发送到邮箱,适合开发测试。生产环境需替换为SMTP配置(如Gmail、企业邮箱等)。
2. 生成邮件类
在终端运行命令生成邮件模板:
rails generate mailer UserMailer send_test_email
这会生成 app/mailers/user_mailer.rb 及对应的视图文件。
3. 编写邮件内容
编辑 app/mailers/user_mailer.rb:
class UserMailer < ApplicationMailer default from: 'your-email@example.com' # 替换为你的发件邮箱 def send_test_email mail(to: 'recipient@example.com', subject: '测试邮件') # 替换为收件邮箱 end end
再编辑邮件视图 app/views/user_mailer/send_test_email.html.erb,添加邮件内容:
<h1>测试邮件</h1> <p>点击按钮成功触发邮件发送!</p>
4. 修改控制器处理POST请求
假设根路径对应 HomeController 的 index 动作,打开 app/controllers/home_controller.rb 添加处理方法:
class HomeController < ApplicationController def index end def send_email UserMailer.send_test_email.deliver_now head :ok # 返回成功状态码,告知前端请求完成 end end
5. 更新路由配置
打开 config/routes.rb,将根路径的POST请求指向 send_email 动作:
root 'home#index' post root_path, to: 'home#send_email'
6. 前端代码优化(可选)
你的现有代码已能发起请求,可添加状态反馈优化体验:
<%= form_tag root_path, class: "send-email" do %> <%= submit_tag "Click to Send Email", style: "margin: 10px; padding: 10px" %> <% end %> <script> document.querySelector(".send-email").onsubmit = function(e) { e.preventDefault() const submitBtn = e.target.querySelector('input[type="submit"]'); submitBtn.disabled = true; submitBtn.value = '发送中...'; fetch(e.target.action, { method: "POST", headers: { "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content } }).then(function(response) { if (response.ok) { window.open('/mail', '_blank'); submitBtn.value = '发送成功!'; setTimeout(() => { submitBtn.value = 'Click to Send Email'; submitBtn.disabled = false; }, 2000); } else { console.error(response); submitBtn.value = '发送失败,请重试'; submitBtn.disabled = false; } }).catch(err => { console.error(err); submitBtn.value = '发送失败,请重试'; submitBtn.disabled = false; }); } </script>
测试运行
启动Rails服务器:
rails s
访问 http://localhost:3000,点击按钮后会自动打开新页面显示测试邮件,前端按钮也会有状态反馈。
内容的提问来源于stack exchange,提问作者bilel abdelmoula
相关产品推荐
相关产品推荐

