Reputation: 1960
In a Rails 5.1 ActionMailer, I want to attach a Mail object to an e-mail:
def attach_mail(original_email)
attachments['original-email.eml'] = { mime_type: 'message/rfc822', encoding: '7bit', content: original_email.to_s }
mail to: 'postmaster', subject: 'mail should be attached'
end
However, this does not produce valid e-mails. Thunderbird lists the attachment with size '0'. Horde lists the attachment with correct size, but does not recognize it as an e-mail.
I've tried variations of the attachments
line:
attachments['original-email.eml'] = original_email
attachments['original-email.eml'] = { content: original_email.to_s }
attachments['original-email.eml'] = { mime_type: 'message/rfc822', content: original_email.to_s }
but none of these result in an e-mail with an e-mail attachment.
What's the solution?
Upvotes: 2
Views: 722
Reputation: 1960
Finally figured it out.
To attach an email (Mail object from the 'mail' gem) to an ActionMailer message, you need to specify the MIME type and encoding like so:
def attach_mail(original_email)
attachments['original-email.eml'] = { mime_type: 'message/rfc822',
encoding: '7bit',
content: original_email.to_s }
mail to: 'postmaster', subject: 'mail should be attached'
end
This creates a multipart/mixed
message which is properly displayed in MUAs.
However, if you happen to add any inline attachment (e.g. to display a logo image in the ActionMailer e-mail body), the entire message will have a multipart/related
mime type. The MUAs that I tried were unable to interpret a multipart/related
message with an e-mail attachment.
Therefore, refrain from adding any inline attachments when attaching an e-mail to an e-mail.
Upvotes: 2