【问题标题】:Mail not being generated properly邮件未正确生成
【发布时间】:2014-05-04 22:11:48
【问题描述】:

我正在尝试使用 rails action mailer 生成邮件,但它似乎并没有完全正确:

这里是我创建邮件的地方:

class UserNotifier < ActionMailer::Base
    default from: 'mail@mail.com'

    def forgot_password(user)
        setup_email(user)
        @subject += "Password restoration"
        @url = url_for :controller => 'user_session', :action => 'reset_password',
                                        :id => user.pw_reset_code, :only_path => true
    end

    protected
    def setup_email(user)
        @subject = "[MY APP] "
        @sent_on = Time.now
        @user = user
        @content_type = "text/html"
        mail to: user.email
    end
end

这是包含邮件的html.erb

<%= @user.name %>,
<br/><br/>
Restore password:
<%= @url %>

但是,邮件的主题并不是我说的那样。

但最重要的是,@urlhtml.erb中是nil,但是在forgot_password中生成正确,我测试了一下。

为什么是nil?我该怎么做才能呈现 URL?

【问题讨论】:

  • 所以你可能说得不对。显示发送电子邮件的代码。

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 actionmailer


【解决方案1】:

当您在 ActionMailer::Base 对象上调用方法 deliver 时发送邮件。
您的方法 forgot_password 未返回此对象。
ma​​il(to: .....) 应该是 forgot_password 例程中的最后一行

运行 rails console 并输入它以查看返回的内容

ActionMailer::Base::mail(to: 'example.com', subject: 'hello')

然后调用#deliver

【讨论】:

    【解决方案2】:

    线

    mail to: user.email
    

    实际上是导致您的电子邮件发送。

    因为您是在 setup_email 中调用它,所以您实际上是在发送电子邮件,然后在发送后尝试更改主题和 URL。

    如果您暂时忽略设置方法,您的代码将按照您当前的顺序显示:

        @subject = "[MY APP] "
        @sent_on = Time.now
        @user = user
        @content_type = "text/html"
        mail to: user.email  << MAIL IS SENT HERE
        @subject += "Password restoration"
        @url = url_for :controller => 'user_session', :action => 'reset_password',
                                        :id => user.pw_reset_code, :only_path => true
    

    更新您的代码以最后调用邮件命令,例如:

    def forgot_password(user)
        setup_email(user)
        @subject += "Password restoration"
        @url = url_for :controller => 'user_session', :action => 'reset_password',
                                        :id => user.pw_reset_code, :only_path => true
        mail to: user.email
    end
    
    protected
    def setup_email(user)
        @subject = "[MY APP] "
        @sent_on = Time.now
        @user = user
        @content_type = "text/html"
    end
    

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多