Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save henrikj242/d9639e871a5a034b37cb925ef56d1e77 to your computer and use it in GitHub Desktop.
Save henrikj242/d9639e871a5a034b37cb925ef56d1e77 to your computer and use it in GitHub Desktop.
Create ActionMailbox::InboundEmail from raw email source

I wanted to fetch emails from an IMAP or POP3 account, and send them to my Rails app with all the benefits from the ActionMailbox, but I couldn't seem to find a well-defined way to do this.

So, I ended up looking at the source of the relay ingress

Here we can see how the controller takes the raw email source and creates the InboundEmail:

ActionMailbox::InboundEmail.create_and_extract_message_id! request.body.read

Here, the request.body.read would return the raw email source from the request being made against the controller.

In my case, I'm talking to an inbox provider over POP3 or IMAP, so here's what I'm doing...

Follow the setup steps in the Action Mailbox guide Skip the step about configuring ingresses.

Run the following to fetch emails from POP3 and create them as InboundEmail objects. ActiveJob and your Mailbox code (as per the guide) will handle the rest.

require 'net/pop'
require 'mail'

# POP3 Server Config
POP3_SERVER = 'mail.example.com'
POP3_PORT = 995
USERNAME = ENV["POP3_USERNAME"]
PASSWORD = Rails.application.credentials.pop3.password

Mail.defaults do
  retriever_method :pop3, { :address             => POP3_SERVER,
                            :port                => POP3_PORT,
                            :user_name           => USERNAME,
                            :password            => PASSWORD,
                            :enable_ssl          => true }
end

Mail.all.each do |mail_obj|

  ActionMailbox::InboundEmail.create_and_extract_message_id!(mail_obj.raw_source)

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