Skip to content

Instantly share code, notes, and snippets.

@sowenjub
Last active January 4, 2023 13:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sowenjub/9917305b2b551a31df9f9ed0ec34d242 to your computer and use it in GitHub Desktop.
Save sowenjub/9917305b2b551a31df9f9ed0ec34d242 to your computer and use it in GitHub Desktop.
A concern adapted from the GoRails ActionMailbox episode https://gorails.com/episodes/save-action-mailbox-html-emails-with-action-text?autoplay=1
# mailboxes/concerns/mail_params.rb
module MailParams
extend ActiveSupport::Concern
def mail_params
attachments = build_attachments
body = build_rich_body(attachments)
{ subject: mail.subject, body: body, attachments: attachments.map { |a| a[:blob] } }
end
def build_attachments
mail.attachments.map do |attachment|
blob = ActiveStorage::Blob.create_after_upload!(
io: StringIO.new(attachment.decoded),
filename: attachment.filename,
content_type: attachment.content_type,
)
{ original: attachment, blob: blob }
end
end
def build_rich_body(attachments)
if mail.multipart? && mail.html_part
document = Nokogiri::HTML(mail.html_part.body.decoded)
attachments.map do |attachment_hash|
attachment = attachment_hash[:original]
blob = attachment_hash[:blob]
if attachment.content_id.present?
# Remove the beginning and end < >
content_id = attachment.content_id[1...-1]
element = document.at_css "img[src='cid:#{content_id}']"
element.replace "<action-text-attachment sgid=\"#{blob.attachable_sgid}\" content-type=\"#{attachment.content_type}\" filename=\"#{attachment.filename}\"></action-text-attachment>"
end
end
document.at_css("body").inner_html.encode("utf-8")
elsif mail.multipart? && mail.text_part
mail.text_part.body.decoded
else
mail.decoded
end
end
end
# models/post.rb
class Post < ApplicationRecord
has_rich_text :body
has_many_attached :attachments
end
# mailboxes/posts_mailbox.rb
class PostsMailbox < ApplicationMailbox
include MailParams
def process
Post.create mail_params
end
end
@sowenjub
Copy link
Author

Alright, then I guess we need to append the attachment.
Also, we may want to delete the signature.
I'll revisit that sometime later, this feature is on pause for a couple of days.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment