【问题标题】:Is it possible to replace default from: with an email from database in Rails Action Mailer?是否可以用 Rails Action Mailer 中数据库中的电子邮件替换默认来自:
【发布时间】:2021-01-14 22:18:19
【问题描述】:

我正在尝试将来自用户的电子邮件传递给默认的 from: 字段,以便看起来它直接来自他们。这是我现在所拥有的。有没有办法将动态变量引入默认字段?

class IntroMailer < ActionMailer::Base
      default from: "Me@gmail.com"

      def intro_email(intro)
        @intro = intro
        mail(to: @intro.person1_email, subject: 'Testing Intro Email')
      end
    end

【问题讨论】:

  • 我搜索了这个答案,但找不到,你能指出我正确的方向吗@mikej
  • 不是重复的。我相信作者正在尝试使用像 lambda 表达式这样的东西作为默认值,就像它在作用域中所做的那样。看起来它没有在 Rails 中实现,但这可以解决。这将需要一些技巧,因为我们无法告诉这个调用背后的用户......
  • 抱歉,加里 - 已更详细地重新阅读了您的问题,并且可以看到它有所不同 - 已重新打开它。

标签: ruby-on-rails ruby ruby-on-rails-4 actionmailer


【解决方案1】:

您可以在 Mailer 操作的 mail 方法中覆盖它:

class IntroMailer < ActionMailer::Base
  default from: "Me@gmail.com"

  def intro_email(intro, current_user)
    mail(to: intro.person1_email, subject: 'Testing Intro Email', from: current_user.email)
  end
end

不过是一个警告。像谷歌这样的电子邮件客户端在检测垃圾邮件方面非常聪明。如果他们看到特定的 SMTP 服务器正在发送具有许多不同“发件人”属性的电子邮件,您的垃圾邮件评级将会上升,并且您的电子邮件将被垃圾邮件过滤器过滤掉。要解决此问题,请选择一两个适合电子邮件类型的默认 from 电子邮件(例如 support@mywebsite.com 和 jobs@mywebsite.com),然后添加一个动态 reply_to 属性。

class IntroMailer < ActionMailer::Base
  default from: "ourteam@oursite.com"

  def intro_email(intro, current_user)
    mail(to: intro.person1_email, subject: 'Testing Intro Email', reply_to: full_from(current_user))
  end

  private

  def full_from(user)
    address = Mail::Address.new user.email
    address.display_name = user.full_name
    address.format
  end
end

【讨论】:

  • 关于reply_to 的好消息。网络应用程序中的电子邮件很难正确处理,很难找到最新信息,这很不幸。
【解决方案2】:

其实不然,在 Rails 5.XX 里根本就不行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2013-05-21
    • 2013-04-14
    • 2015-08-23
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多