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

如何为Devise邮件内容添加环境条件判断?

解决Devise邮件添加环境专属信息的方案

方法1:自定义Devise邮件模板(最直观)

Devise默认邮件模板封装在gem中,你可以先将模板生成到项目本地,直接在模板里用ERB语法插入环境变量:

  1. 生成邮件模板到项目:
rails generate devise:views mailer

执行后,app/views/devise/mailer/目录会出现所有Devise邮件模板(如reset_password_instructions.html.erb、reset_password_instructions.text.erb)。

  1. 修改模板内容:
    打开对应模板,在标题或正文加入环境标识逻辑,比如仅非生产环境显示提示:
<% unless Rails.env.production? %>
  <div style="background: #fff3cd; padding: 10px; text-align: center; font-weight: bold;">
    【<%= Rails.env.upcase %>环境】此邮件为测试用途,请勿用于正式操作
  </div>
<% end %>

<h2><%= Rails.env.production? ? '' : "[#{Rails.env.upcase}] " %>重置密码指引</h2>

方法2:重写Devise邮件的subject方法(集中管理)

若不想修改模板,可通过重写邮件类方法动态设置主题:

  1. 在app/mailers/创建custom_devise_mailer.rb:
class CustomDeviseMailer < Devise::Mailer
  def reset_password_instructions(record, token, opts = {})
    env_prefix = Rails.env.production? ? '' : "[#{Rails.env.upcase}] "
    opts[:subject] = "#{env_prefix}#{I18n.t('devise.mailer.reset_password_instructions.subject')}"
    super(record, token, opts)
  end

  # 同理可重写确认邮件等其他Devise邮件方法
  def confirmation_instructions(record, token, opts = {})
    env_prefix = Rails.env.production? ? '' : "[#{Rails.env.upcase}] "
    opts[:subject] = "#{env_prefix}#{I18n.t('devise.mailer.confirmation_instructions.subject')}"
    super(record, token, opts)
  end
end
  1. 在config/initializers/devise.rb配置使用自定义邮件类:
Devise.setup do |config|
  config.mailer = 'CustomDeviseMailer'
end

方法3:让YAML文件支持ERB解析(需全局配置)

Rails默认不解析locale YAML中的ERB,可修改config/application.rb开启预处理:

module YourAppName
  class Application < Rails::Application
    # 替换原有i18n加载路径配置,让YAML文件经过ERB解析
    config.i18n.load_path = Dir[Rails.root.join('config', 'locales', '**', '*.yml')].map do |path|
      ERB.new(File.read(path)).result
    end
  end
end

随后将devise.en.yml改名为devise.en.yml.erb,即可在其中使用ERB语法:

en:
  devise:
    mailer:
      reset_password_instructions:
        subject: "<%= Rails.env.production? ? '' : "[#{Rails.env.upcase}] " %>Reset password instructions"

注意:此方法会影响所有locale文件的加载逻辑,需测试验证兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:36:20