2

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

电子邮件.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
4

1 回答 1

7

看起来我又在回答我自己的问题了——这周我很开心。

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

新编辑:暂无关于 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/文本部分(即完全呈现的视图)的邮件对象,但更改了这些视图使用的属性(在我的情况下,是“内容”属性)螺丝最后发送。发送前不要修改你的模型,直接修改邮件部分。

于 2013-02-24T22:05:41.773 回答