rails - Parsing an Email Message for just the reply, not the old thread?
I set my app to receive incoming emails via a post from a service. The controller that receives the posts looks a little like this:
class IncomingMailsController < ApplicationController
require 'mail'
skip_before_filter :verify_authenticity_token
def cre开发者_Go百科ate
message = Mail.new(params[:message])
message_plain = (params[:plain])
Rails.logger.info 'message2.plain:'
Rails.logger.info message2
render :text => 'success', :status => 200 # a status of 404 would reject the mail
end
end
That successfully is delivering the entire email message, replies,forward history etc. The issue is I'd like to be able to extract just the actual reply text.
Currently I get:
That's not a bad idea. Lets try that out.
On Nov 17, 2010, at 4:18 PM, XXXXX @ XXXXXXXX wrote:
> There's a new reply:
And I'd like to know how rails devs get just the reply:
That's not a bad idea. Lets try that out.
Ideas? Thanks
There's no guaranteed way to get the entire message however it's common practice to make use of a separator and then use some code to parse out the response line.
If you take a look at the code in the open source project teambox for example you see the something really similar to the following:
def strip_responses(body)
# For GMail. Matches "On 19 August 2010 13:48, User <proj+conversation+22245@app.teambox.com<proj%2Bconversation%2B22245@app.teambox.com>> wrote:"
body.strip.
gsub(/\n[^\r\n]*\d{2,4}.*\+.*\d@app.teambox.com.*:.*\z/m, '').
split("---------separator---------").first.
split("<div class='email'").first.
strip
end
Not a perfect gem, but you could try this gem from Github: Email Reply Parser
Have a look at the extended_email_reply_parser, which also includes github's email_reply_parser.
Install
Add it to the Gemfile
:
# Gemfile
gem 'extended_email_reply_parser'
Usage
Then, you can parse the email reply like this:
message_plain = ExtendedEmailReplyParser.parse message
Example
Applied to your code:
class IncomingMailsController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
message = Mail.new(params[:message])
message_plain = ExtendedEmailReplyParser.parse(message)
render :text => 'success', :status => 200 # a status of 404 would reject the mail
end
end
email_reply_parser vs. extended_email_reply_parser
The email_reply_parser is used and developed by github. It's small and efficient, but can't handle some edge cases, where the sender's email client doesn't properly format the previous conversation as quote.
The extended_email_reply_parser is an extendible wrapper around github's parser. It's not as efficient as the original one. But, it's easier to extend if the typical emails you're parsing are not handled quite right out of the box.
Resources
- email_reply_parser
- extended_email_reply_parser
- Examples for extending the parser
精彩评论