2

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

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 

回答

6

看起来像我回答我的问题再次 - 这个星期我在一个卷。

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

新的编辑:划伤我最后一个关于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 

澄清: 即使调用邮件()产生具有完全呈现HTML /文字部分邮件的对象(即完全渲染视图) ,改变这些视图使用的属性(在我的情况下,'内容'属性)将最终发送的内容锁定。请勿在发送之前修改模型,直接修改邮件部分。

相关问题