如何在 ActiveMailer 中将 base64 图像作为内联附件添加到邮件中?

How to add base64 images as inline attachment to a mail in ActiveMailer?

我正在尝试使用 Active Mailer 在 rails 上的 Ruby 中将 base64 图像作为内联附件发送,但它不起作用。

我找到了这种添加附件的方法:

def inline_base64(name, content)
    attachments.inline[name] =
    {
      mime_type: 'image/png',
      content: content,
      encoding: "base64"
    }
  end

我这样调用方法

inline_base64('first_client.png', client[:image64])

其中第一个参数只是名称,另一个是作为字符串的 base64 图像

在 erb 文件中,我尝试插入像这样的图像:

<%= image_tag attachments['first_client.png'].url, size:'90' %>

但是当我收到邮件时,它只显示图像损坏:

有人知道我该怎么做吗?

Base64 是文件中数据的编码表示。

Note the difference between Base64 and DataURL.

DataURL strings start with data:image/png;base64, or a similar string. If this is your case, then your base 64 encoded data is everything after the ,: base_64 = content.split(',')[1]

这个 base 64 数据只是读取文件并将其数据编码为 base 64 的结果:

content = Base64.encode64(File.read('your/path.png'))

您只需撤消编码即可获得与函数File.read return:

完全相同的结果
data = Base64.decode64(content)

您的方法将如下结束:

def inline_base64(name, content)
  attachments.inline[name] = Base64.decode64(content)
end

如果您的图像仍然损坏,请检查您的 content 是否以 DataURL 字符串开头并将其删除。