首页 > 解决方案 > 如何发送带有图像背景的电子邮件而不将此图像附加为文件以供下载?

问题描述

我发送电子邮件,它正在按我的意愿工作,但是当电子邮件到达时,它附带了我用作消息背景的附加图像

这就是我在电子邮件中添加图像的方式

<div style="background-image:url('<%= email_bg_tag("bg-email.jpg") %>');background-position:top center;background-repeat:no-repeat;background-color:transparent;">

这是我的 email_helper.erb

module EmailHelper
  def email_bg_tag(image)
    attachments[image] = File.read(Rails.root.join("app/assets/images/#{image}"))
    attachments[image].url
  end
end

我的图片在assets/image

标签: ruby-on-railsrubyhtml-emailsendgrid

解决方案


跳过静态图像的资产管道以在您的电子邮件中工作,您应该将它们放入:

Rails.root + 'public/images'

然后在我们的电子邮件中,您应该使用带有完整 url 的 css 到图像:

 background-image:url('http://yoursite.com/public/images/background.jpg');

我建议在您的邮件中使用样式标签,然后像这样添加类:

<style>
  .my-fancy-background {
    background-image: url('http://yoursite.com/public/images/bg-email.jpg');
    background-position: top center;
    background-repeat: no-repeat;
    background-color: transparent;
  }
</style>
<div class="my-fancy-background">
  Here is my email div with some fancy background  
</div>

但是如果你仍然想要辅助方法,你可能还需要在 application.rb 中设置它

config.action_mailer.asset_host = 'http://example.com/public/' 
# use public url of your app where your static images can be served from. 
更新

根据 gwally 的评论,Outlook 可能不支持此功能,因此如果您关心 Outlook 是否支持此功能,您可能想看看这里


推荐阅读