Rails 电子邮件解析

Rails Email Parsing

我希望我的 rails 应用程序能够接收传入的电子邮件并以特定方式解析它们。

incoming_controller.rb

class IncomingController < ApplicationController
  skip_before_action :verify_authenticity_token, only: [:create]
  skip_before_action :authenticate_user!, only: [:create]
  def create
    # Find the user
     user = User.find_by(email: params[:sender])

     # Find the topic
     topic = Topic.find_by(title: params[:subject])

     # Assign the url to a variable after retreiving it from
     url = params["body-plain"]

     # If the user is nil, create and save a new user
     if user.nil?
       user = User.new(email: params[:sender], password: "password")
       user.save!
     end

     # If the topic is nil, create and save a new topic
      if topic.nil?
        topic = Topic.new(title: params[:subject], user: user)

        topic.save!
      end

      bookmark = topic.bookmarks.build(user: user, url: url, description: "bookmark for #{url}")

      bookmark.save!

    # Assuming all went well.
    head 200
  end
end

使用这个控制器我只能提取 3 个值 = user :sender, topic :subject 和 url "body-plain".

如何在电子邮件中添加第 4 个值来解析 :description?

params[:description] 实现理论上应该与您的方法中使用的其他 params 项目一样工作,您只需要确保调用您的 IncomingController#create 操作的任何内容都在发送一个 :description 参数。

或者,如果您无法将参数添加到任何调用控制器操作的对象中,也许您可​​以将其添加到您当前用于 urlparams['body-plain'] 中?您可以使用序列化文本格式在电子邮件正文中存储多个字段,例如(使用 YAML):

url: http://example.com
description: I'm a description

然后在您的控制器中,您将像这样解析该字段:

class IncomingController < ApplicationController
  require 'yaml'
  def create
    # ...
    body_params = YAML.load(params['body-plain'])
    url = body_params[:url]
    description = body_params[:description]
    # ...
  end
end