开发者

Reading binary data from database and use as attachement in mail with Ruby on Rails

开发者 https://www.devze.com 2023-02-08 01:00 出处:网络
I read the content of a file on my client, base64 encode it, send it via JSON to my Rails backend, base64 decode it and store the data in the database. I then try to send a email from Rails with the d

I read the content of a file on my client, base64 encode it, send it via JSON to my Rails backend, base64 decode it and store the data in the database. I then try to send a email from Rails with the data as a attachement.

Here is my column definition of the binary data:

t.column :binarydata, :binary, :limit => 10.megabytes, :null => false

Here is my mail template:

class MYMailer < ActionMailer::Base
  def mail(from, to, cc, bcc, subject, message, files=[], sent_at = Time.now)
    @subject = subject
    @recipients = to
    @from = from
    @cc = cc
    @bcc = bcc
    @sent_on = sent_at
    @body["message"] = message
    @headers = {}

    # attache files
    files.each do |file|
      attachment file.mimetype do |a|
        a.body = file.binarydata
        a.filename = file.filename
      end
    end

  end
end

Here is where I read from the database and send the email:

attachements = AttachementItem.find(:all)
MYMailer.deliver_mail("foo@home.com", "bar@home.com", nil, nil, "Attachement test", "This is just a test", attachements)

Here is the code that parses the incomming JSON and stores the data in the database:

attachement_json = params[:attachement]
attachement_json = attachement_json.gsub(/\n/, "\\n")
attachement = AttachementItem.new.from_json(attachement_json)
b64data = Base64.decode64(attachement.binarydata)
attachement.binarydata = b64data
a开发者_如何转开发ttachement.save

However the attachements that I receive in my email is garbage. I do not know if the error is on my client side and I am investigation this also, but can you see if I have a error in my Rails code?

Thank you


Well my Rails code works! I found my errors (there where more than one), and they where all in my client code. Sorry for asking :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号