[英]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. 我想要的是一种获取此信息并将其插入数据库的方法,我知道ActionMailer :: Base中有一个方法称为接收。 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. 是的,这是正确的方法,只是Google“接收带有红宝石的邮件”-有很多教程可以指导您。
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. 这看起来像JSON,因此您只需让JSON解析器完成工作,它将为您提供适当的Ruby数据结构。 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. 看看Fetcher ,它对我一直很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.