繁体   English   中英

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

[英]How to modify actionmailer email html_part before sending

我即将发送电子邮件,但我需要修改所有链接以包含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

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

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

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

另一个编辑:最后?

在我执行apply_url_tracker方法之前,我已经重置了电子邮件的内容(为了更改渲染视图中的所有链接)。 我不知道为什么考虑到邮件的Mail对象的螺丝应该已经呈现,但是将我的方法更改为以下内容可以修复电子邮件部分的重复及其随后的“重新编码”。 我不再更改content属性,只更改了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”属性)最后发送。 发送前请勿修改您的型号,只需直接修改邮件部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM