如何在发送之前修改actionmailer email html_part

时间:2013-02-23 18:27:43

标签: ruby-on-rails ruby-on-rails-3 email actionmailer html-email

我即将发送电子邮件,但我需要修改所有链接以包含Google Analytics(分析)属性。问题是,如果我尝试读取/写入电子邮件的html_part.body,整个html字符串会以某种方式编码,并且不会正确显示电子邮件(即<html>变为&lt;html&gt;)。我在记录器中记录了html_part.body.raw_source,它显示为正确的未编码HTML,只有当电子邮件实际发送时才会发生编码。

EBlast.rb(ActionMailer)

def main(m, args={})

    # Parse content attachment references (they don't use helpers like the layout does)
    # and modify HTML in other ways
    m.prep_for_email self

    @email = m # Needed for helper methods in view
    mail_args = {
    :to => @user.email,
    :subject => m.subject,
    :template_path => 'e_blast',
    :template_name => 'no_template'
    }
    mail_args[:template_name] = 'main' if m.needs_template?

    m.prep_for_sending mail(mail_args)
end

Email.rb

def prep_for_sending(mail_object)

    if mail_object.html_part

    # If I simply do a 'return mail_object', the email sends just fine...
    # but the url trackers aren't applied.

    # Replace the content with the entire generated html
    self.content = mail_object.html_part.body.decoded

    # Add Google analytics tracker info to links in content
    apply_url_tracker :source => "Eblast Generator", :medium => :email

    # Replace the html_part contents
    mail_object.html_part.body = content

    # At this point, mail_object.html_part.body contains the entire
    # HTML string, unencoded. But when I send the email, it gets its
    # entities converted and the email is screwed.

    end

    # Send off email
    mail_object

end

1 个答案:

答案 0 :(得分:6)

看起来我再次回答了我自己的问题 - 本周我就开始了。

显然直接设置主体会创建一个名为'body_raw'的奇怪属性,而不是替换html_part的raw_contents。所以基本上我最终在邮件对象中嵌入了一个重复的部分(我不知道为什么会这样做)。创建一个单独的Mail :: Part并将其分配给html_part只是添加了另一部分而不是替换html_part! WTF?!

New Edit:抓住我关于String.replace的最后一句话。看起来它工作正常,但当我去另一台计算机并进行测试时,发生了同样的重复问题。

另一个编辑:最后?

在我执行apply_url_tracker方法之前,我已经重置了电子邮件的内容(为了更改渲染视图中的所有链接)。我不知道为什么考虑到消息的邮件对象的螺钉应该已经呈现,但是将我的方法改为以下内容已经修复了电子邮件部分的复制及其随后的“重新编码”。我不再更改内容属性,我只更改了html_part:

def prep_for_sending(message)

    if message.html_part
    # Replace the html raw_source
    message.html_part.body.raw_source.replace apply_url_tracker(message.html_part.body.decoded, :source => "Eblast Generator", :medium => :email)
    end

    message

end

澄清: 即使对mail()的调用产生了一个带有完全呈现的HTML / Text部分的Mail对象(即完全呈现的视图),更改这些视图使用的属性(在我的例子中,'content'属性)会搞砸最终发送。发送前请勿修改您的型号,只需直接修改邮件部分。

相关问题