views:

135

answers:

1

I want to store emails into a database and then have them displayed properly in Ruby on Rails to the user (ideally with a nicely formatted, collapsible header, attachment support, etc). Is there already a good way to do this?

Right now, I store the emails to the database as a text, but I am struggling with a good way to display them to the user on the rails page?

Any suggestions? I am opening to changing the way I store the email to the database if there is a better way.

Thanks in advance!

+1  A: 

You might want to look at the TMail library, which comes with rails (and is updateable on its own). Let's assume you have a model called Message which corresponds to the table holding the mails, and that an attribute/column called raw_mail holds the raw mail text.

You can then instantiate an TMAil::Mail object and work with it like that:

@email = TMail::Mail.parse(Message.find(params[:id]).raw_mail)

That provides you, e.g., with:

@email.body # => Dear NoahD, how are you? I'm fine...
@email.subject # => Hello from New Zealand
@email.has_attachment? #=> true
@email.attachments.first.original_filename # => kiwi.jpg

As far as storing the mail goes: Mails can contain non-ASCII characters, so perhaps you have to make sure that the column type chosen for raw_mail by ActiveRecord is actually able to handle those data. I think :binary is a good choice there.

cite