简体   繁体   中英

Parsing emails with ActionMailer::Base receive method

I want to know if there is a way to parse a received email.

For example, someone sends me the following email:

  {
      product: "x_product",
      quantity: "1",
      price: "15",
  }

What I want is a way to get this information and insert it in the database I know there is a method in ActionMailer::Base called receive. Is this the correct approach? How to parse this?

Yes this is the correct approach, just google "receive mails with ruby on rails" - there are plenty of tutorials to guide you.

The parsing depends on the kind of data you are about to receive. This looks like JSON, so you'd simply let a JSON parser do the work and it will give you a proper Ruby data structure. The rest (putting it into a DB) can be handled by a model.

It would look a bit like this:

class MailReceiver < ActionMailer::Base

  def self.receive(message)
    # depending on your Rails version you can use either TMail or Mail to parse the raw mail
    mail = TMail::Mail.parse(message)

    # parse the JSON
    my_data = ActiveSupport::JSON.decode(mail.body)

    # create something with the data
    MyModel.create(my_data)
  end

end

I did not cover the actual fetching of the mails from a mailbox. Again: google it, there are tons of tutorials out there. Have a look at Fetcher , which has always served me well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM