Ruby on Rails中如何在Ruby变量字符串开头插入HTML图片
Rails自动邮件开头插入HTML图片实现方法
你当前的代码需要做两处基础调整才能实现需求:
- 原代码设置的内容类型为
text/plain纯文本格式,该格式无法解析任何HTML标签,自然无法渲染图片,必须先切换为text/html类型 - 原代码正文拼接处存在多余单引号的语法错误,调整时一并修复即可
具体实现步骤
- 配置邮件资源路径
如果你使用项目app/assets/images目录下的静态图片,先在对应环境的配置文件(比如生产环境的config/environments/production.rb)中添加配置,确保邮件内图片路径可被正常解析:config.action_mailer.asset_host = '你的服务部署域名' - 在正文最开头拼接图片标签
直接使用Rails内置的image_tag辅助方法生成图片标签,拼接到整个value字符串的最起始位置即可,修改后的完整代码如下:content = Content.new( type: 'text/html', value: ( image_tag('rocket-team-logo.png', alt: 'Rocket Elevators 标识', style: 'max-width: 200px; margin-bottom: 20px;') + 'Greetings ' + @lead.name + ', We thank you for contacting Rocket Elevators to discuss the opportunity to contribute to your project ' + @lead.project_name + '. A representative from our team will be in touch with you very soon. We look forward to demonstrating the value of our solutions and helping you choose the appropriate product given your requirements. We’ll Talk soon The Rocket Team ' ) ) - (可选)使用内联附件避免图片被拦截
如果担心邮箱客户端拦截外部图片资源,可以将图片作为内联附件嵌入邮件:# 先在邮件发送的action方法中添加内联附件 attachments.inline['rocket-logo.png'] = File.read(Rails.root.join('app/assets/images/rocket-team-logo.png')) # 正文拼接时引用内联附件地址 content = Content.new( type: 'text/html', value: ( image_tag(attachments['rocket-logo.png'].url, alt: 'Rocket Elevators 标识', style: 'max-width: 200px; margin-bottom: 20px;') + 'Greetings ' + @lead.name + ', We thank you for contacting Rocket Elevators to discuss the opportunity to contribute to your project ' + @lead.project_name + '. A representative from our team will be in touch with you very soon. We look forward to demonstrating the value of our solutions and helping you choose the appropriate product given your requirements. We’ll Talk soon The Rocket Team ' ) )
注意:如果需要兼容不支持HTML渲染的老旧邮箱客户端,可以额外新增一个
type: 'text/plain'的Content对象传入纯文本版本的正文,Rails会自动根据客户端能力匹配展示对应内容,纯文本版本不要添加任何HTML标签。
内容的提问来源于stack exchange,提问作者BanasCode
相关产品推荐
相关产品推荐

