mikel / mail

A Really Ruby Mail Library
MIT License
3.6k stars 931 forks source link

Forward email doesn't encode the attachment correctly #1580

Closed dpaluy closed 1 year ago

dpaluy commented 1 year ago

I have a Mail::Message that I received with ActionMailbox. This message has an attachment PDF.

I want to forward it to another address. But when I send it, it does additional encoding of the attached file, and the PDF is broken in the recipient mailbox.

original_message = ActionMailbox::InboundEmail.find(12345).mail
mail = original_message.dup
mail.from = "test@example.com"
mail.to = "new_address@example.com"
ActionMailer::Base.wrap_delivery_behavior(mail)
mail.deliver

The result is a broken PDF, because the attachment is Base64. (If I decode Base64, I receive correct PDF)

The only solution that works for me is:

attachments = original_message.attachments
attachment = attachments.first
content = attachment.decoded
mail.attachments[attachment.filename] = content
mail.attachments.first.body = content

But this one adds a new file, and the recipient gets 2 attachments (1 broken and 1 correct)

What is the correct way to forward the email with attachments?

Thank you

dpaluy commented 1 year ago

The following solution resolved the issue:

new_mail.attachments.each do |attachment|
  attachment.body = attachment.body.decoded
  attachment.body_encoding = "binary"
end

However, I don't understand why we need explicitly change the encoding and can't reuse the current one.