We're currently letting users email each other without seeing each other's actual email addresses (double blind) by letting them send emails to [email protected] which works great.
class ForwardsMailbox < ApplicationMailbox
before_processing :ensure_users
def process
content = mail.multipart? ? mail.parts.first.body.decoded : mail.decoded
UserMailer.with(sender: sender, recipient: recipient, subject: mail.subject, content: content).forward_email.deliver_later
end
private
def sender
@sender ||= User.find_by(email: mail.from.first)
end
def recipient
@recipient ||= User.find_by(username: mail.to.first.split('@').first)
end
def ensure_users
bounce_with UserMailer.invalid_user(inbound_email) if sender.nil? or recipient.nil?
end
end
Is it possible to forward the whole mail object instead of extracting its contents, checking if it is multipart etc?
Try to give this a shot. Reuse the mail object in your
processmethod and directly deliver the message yourself. You'll need to reach into ActionMailer to get your delivery methods configured correctly, but I believe it'll work.How this works:
Behind the scenes Mailers are just calling
deliveron aMailobject to send emails. You can go peruse throughActionMailer::MessageDeliveryif you'd like to see that in action. We're just using that functionality directly here.I'd recommend staying away from using Mailers in this instance because copying over all the fields from your original mail object to the mailer's mail object is going to require a lot of trial and error.
One thing to note: the headers remain unchanged when the message is re-delivered, so things like
Message-IDwill still be the same (which may or may not be a problem, just something to consider).Last, if you're concerned at all about
deliverbeing a blocking call to an API/SMTP server like I was, worry not! It looks like ActionMailbox already ensures that theprocessmethod runs via ActiveJob, so you shouldn't have to worry about an SMTP/API request taking a while and blocking a web request (see ActionMailbox guides).