ruby-on-railsparsingemailincoming-mail

How can I parse an email passed as a string in Rails 3


I'm using a postfix mail server and I'm sending incoming emails to a controller through an alias:

v2mail1: |"/var/www/html/dev/rails/v2p0/script/email_handler.sh incoming_email development"

In the email_handler.sh I'm passing the email from the standard input to the controller as a POST message:

/usr/bin/curl -F email='<-' -s -f $base_url/$1

So I get the whole email as a string in the controller. How can I parse this string to get to, cc, subject, body, attachments, etc. I did not find any gem for that. E.g. the string:

"From nagyt@hu.inter.net  Fri Jun 27 11:14:28 2014\nReturn-Path: <nagyt@hu.inter.net>\nX-Original-To: v2mail1\nDelivered-To: v2mail1@centos1.tibi1959.hu\nReceived: by centos1.tibi1959.hu (Postfix, from userid 276)\n\tid C0DC7283A04; Fri, 27 Jun 2014 10:18:59 +0200 (CEST)\nDate: Fri, 27 Jun 2014 10:18:59 +0200\nTo: v2mail1@centos1.tibi1959.hu\nSubject: test from ntibor to v2mail1\nUser-Agent: Heirloom mailx 12.5 7/5/10\nMIME-Version: 1.0\nContent-Type: text/plain; charset=us-ascii\nContent-Transfer-Encoding: 7bit\nMessage-Id: <20140627081859.C0DC7283A04@centos1.tibi1959.hu>\nFrom: nagyt@hu.inter.net (Nagy Tibor)\n\nTest\n"

Solution

  • I've found the simplest way to parse the raw email text:

    mail = Mail.new raw_mail
    

    In that case mail is an instance of Mail::Message, with all of the methods I need to access mail attributes, attachments easily.