Tyr*_*son 67
我将Oksana的答案与自定义助手方法结合起来,并使得以下工作非常好.
app/helpers/email_helper.rb
module EmailHelper
def email_image_tag(image, **options)
attachments[image] = File.read(Rails.root.join("app/assets/images/#{image}"))
image_tag attachments[image].url, **options
end
end
Run Code Online (Sandbox Code Playgroud)
app/mailers/base_mailer.rb
class BaseMailer < ActionMailer::Base
add_template_helper(EmailHelper)
end
Run Code Online (Sandbox Code Playgroud)
app/mailers/my_mailer.rb
class MyMailer < BaseMailer
def send_my_mail(email)
mail to: email, subject: "My Subject"
end
end
Run Code Online (Sandbox Code Playgroud)
然后,例如,我想在我的电子邮件布局文件中附加公司徽标,我会使用
app/views/layouts/email.html.erb
<%= email_image_tag("company_logo.png") %>
注意**选项使标记更具可扩展性,但它只能在ruby> = 2中使用.要使这个工作在ruby <2中,你将不得不使用旧方法来处理关键字选项.
Joe*_*oel 35
铁路5
在您的邮件方法中添加指向图像的内联附件:
class ConfirmationMailer < ActionMailer::Base
def confirmation_email
attachments.inline["logo.png"] = File.read("#{Rails.root}/app/assets/images/logo.png")
mail(to: email, subject: 'test subject')
end
end
Run Code Online (Sandbox Code Playgroud)
然后在你的邮件html视图中image_tag
使用附件url:
<%= image_tag(attachments['logo.png'].url) %>
Run Code Online (Sandbox Code Playgroud)
Pav*_*lli 21
添加到Oksana和tdubs的答案
模块tdubs在桌面上编写了作品,但对于移动gmail客户端,图像显示为附件.要解决此问题,请执行此操作
应用程序/佣工/ email_helper.rb
module EmailHelper
def email_image_tag(image, **options)
attachments[image] = {
:data => File.read(Rails.root.join("app/assets/images/emails/#{image}")),
:mime_type => "image/png",
:encoding => "base64"
}
image_tag attachments[image].url, **options
end
end
Run Code Online (Sandbox Code Playgroud)
其余的,请按照tdubs的回答.
Aam*_*mir 13
经过大量的研究,我发现在电子邮件中嵌入图像非常简洁.只需添加以下行production.rb
和development.rb
config.action_mailer.asset_host = 'YOUR HOST URL'
Run Code Online (Sandbox Code Playgroud)
在您的视图中使用以下代码嵌入图像.
<%= image_tag('My Web Site Logo.png') %>
Run Code Online (Sandbox Code Playgroud)
注意:请务必在上面的代码中更新您的主机URL和My Web Site Logo.png.
有关Action Mailer用法的基本信息,请参阅ActionMailer :: Base.
从此处复制粘贴
http://api.rubyonrails.org/classes/ActionMailer/Base.html#class-ActionMailer::Base-label-Inline+附件
内联附件
您还可以指定文件应与其他HTML内联显示。如果要显示公司徽标或照片,这很有用。
class Notifier < ApplicationMailer
def welcome(recipient)
attachments.inline['photo.png'] = File.read('path/to/photo.png')
mail(to: recipient, subject: "Here is what we look like")
end
end
Run Code Online (Sandbox Code Playgroud)
然后要引用视图中的图像,请创建一个welcome.html.erb文件,并调用image_tag并传递要显示的附件,然后在附件上调用url以获取图像的相对内容ID路径资源:
<h1>Please Don't Cringe</h1>
<%= image_tag attachments['photo.png'].url -%>
Run Code Online (Sandbox Code Playgroud)
当我们使用Action View的image_tag方法时,您可以传入所需的任何其他选项:
<h1>Please Don't Cringe</h1>
<%= image_tag attachments['photo.png'].url, alt: 'Our Photo', class: 'photo' -%>
Run Code Online (Sandbox Code Playgroud)
reg*_*gex -2
我对 Rails 不太了解,但我曾参与过 C# 项目,这些项目创建电子邮件,然后通过 Google API 将其插入用户收件箱。要创建电子邮件,我必须从头开始生成电子邮件字符串。如果您为电子邮件启用多部分,则图像字节将包含在使用 base64 编码的多部分部分中。
您可能需要查看 TMail 和 RubyMail 软件包,看看它们是否支持您的这些操作。
归档时间: |
|
查看次数: |
27530 次 |
最近记录: |