Mohamed El Mahallawy
Mohamed El Mahallawy

Reputation: 13842

Rails mailer image attachment from data uri

I have saved a signature which is in the form of a image data uri, png and stored in my database as a string.

When sending an email, I want to attach it inline but the image keeps showing up as not working in Gmail. Here is my code:

Mailer:

attachments.inline['signature'] = {
  content: @project_addition.signature.split(',')[1],
  mime_type: 'image/png',
  encoding: 'base64'
}

View:

<%= image_tag attachments.inline['signature'].url, width: '25%' %>

First few chars of the string:

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABowAAAC4CA....

Upvotes: 1

Views: 982

Answers (2)

Osvaldo Perez
Osvaldo Perez

Reputation: 27

if you don't have the image data uri, another solution is put below method in your helper

app/helpers/email_helper.rb

  def email_data_uri(image, **options)
    code = File.open("#{Rails.root}/app/assets/images/#{image}", 'r').read
    data = Base64.strict_encode64(code)
    type = image.split('.')[-1]
    name = image.split('/')[-1]
    attachments.inline[name] = {
      content: Base64.decode64(data),
      mime_type: "image/#{type}"
    }
    image_tag attachments.inline[name].url, **options
  end

app/view/campaign_mailer

= email_data_uri 'email/livechat-logo.png', style: 'width: 34px'

adding the style options

Upvotes: 2

amitamb
amitamb

Reputation: 1067

You need to call Base64.decode64 to decode the base64 encoded content and not specifiy encoding

attachments.inline['signature'] = {
  content: Base64.decode64(@project_addition.signature.split(',')[1]),
  mime_type: 'image/png'
}

Upvotes: 1

Related Questions