You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生产环境下Rails Mailer Previews报“Unknown action preview not found”原因

生产环境启用Rails邮件预览遇404问题解决指南

我正尝试在生产环境启用Rails邮件预览(已知存在安全风险,计划通过猴子补丁为Rails::MailersController添加身份验证)。已在production.rb中设置config.action_mailer.show_previews = true,但访问时仍返回404,错误日志如下:

2024-03-28T17:48:38.809127+00:00 app[web.1]: [a7572d16-cbd1-4246-9f13-42c840b079d9] Started GET "/rails/mailers/donor_mailer/welcome_email" for 174.228.100.24 at 2024-03-28 17:48:38 +0000
2024-03-28T17:48:38.809714+00:00 app[web.1]: [a7572d16-cbd1-4246-9f13-42c840b079d9] Processing by Rails::MailersController#preview as HTML
2024-03-28T17:48:38.809732+00:00 app[web.1]: [a7572d16-cbd1-4246-9f13-42c840b079d9]   Parameters: {"path"=>"donor_mailer/welcome_email"}
2024-03-28T17:48:38.810160+00:00 app[web.1]: [a7572d16-cbd1-4246-9f13-42c840b079d9] Completed 404 Not Found in 0ms (ActiveRecord: 0.0ms | Allocations: 179)
2024-03-28T17:48:38.811846+00:00 app[web.1]: [a7572d16-cbd1-4246-9f13-42c840b079d9]

一、解决404问题:让生产环境加载邮件预览文件

Rails默认仅在开发/测试环境加载test/mailers/previews或spec/mailers/previews目录,生产环境需手动配置加载逻辑:

  1. 在config/production.rb中添加预览路径与加载配置:
# 指定邮件预览类的存放目录(根据项目用test或spec目录)
config.action_mailer.preview_path = Rails.root.join('test/mailers/previews')

# 确保生产环境加载预览目录下的所有文件
Rails.application.config.to_prepare do
  Dir.glob(Rails.root.join(config.action_mailer.preview_path, '**/*.rb')).each do |file|
    require_dependency file
  end
end
  1. 确认预览类命名与结构合规:
    比如对应DonorMailer的预览类需命名为DonorMailerPreview,存放在test/mailers/previews/donor_mailer_preview.rb,并包含目标预览方法:
class DonorMailerPreview < ActionMailer::Preview
  def welcome_email
    # 传入合法测试数据,确保邮件能正常生成
    DonorMailer.welcome_email(Donor.first)
  end
end

二、添加身份验证:给Rails::MailersController打猴子补丁

创建config/initializers/mailers_controller_auth.rb,添加HTTP Basic认证逻辑(也可替换为项目已有权限验证体系):

module Rails
  class MailersController
    before_action :authenticate_mail_preview_access!

    private

    def authenticate_mail_preview_access!
      authenticate_or_request_with_http_basic do |username, password|
        # 从环境变量读取验证凭据,避免硬编码
        username == ENV['MAILER_PREVIEW_USER'] && password == ENV['MAILER_PREVIEW_PASS']
      end
    end
  end
end

在生产环境配置MAILER_PREVIEW_USER和MAILER_PREVIEW_PASS两个环境变量。

三、验证效果

重启生产环境服务器后,访问/rails/mailers/donor_mailer/welcome_email,输入配置的用户名密码,确认邮件预览正常显示。

内容的提问来源于stack exchange,提问作者Jason FB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 00:52:46