【问题标题】:Rails Email ParsingRails 邮件解析
【发布时间】:2016-08-12 07:56:03
【问题描述】:

我希望我的 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 个值 = 用户:发件人、主题:主题和 url “body-plain”。

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

【问题讨论】:

    标签: ruby-on-rails email-parsing


    【解决方案1】:

    理论上,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
    

    【讨论】:

    • 如何设置电子邮件中的文本以便将其识别为描述?例如,我将电子邮件的主题设置为等于主题。我可以从电子邮件中设置什么来等同于描述?
    • 这取决于调用您的控制器的内容...我假设您有某种电子邮件接收设置,它将电子邮件解析为哈希并提交给您的控制器操作?如果您可以控制它,您可以将参数添加到哈希中。如果你不能这样做,你可以像我在我编辑的答案中解释的那样将它添加到电子邮件正文中。
    • 我正在尝试您在答案中概述的方法,但参数没有选择 URL 和描述。它将它们都读取为 nil。
    • 当我在我的测试应用程序中测试基本行为时,它可以工作。您是否将 YAML.load 结果存储到您自己的变量中(例如我的示例中的 body_params),然后访问 url 和描述(例如 body_params[:url])?并且仅将params 用于其他字段?如果您在尝试时没有看到整个控制器,很难说是什么不工作。
    猜你喜欢
    • 2014-07-18
    • 2010-12-01
    • 2012-06-01
    • 1970-01-01
    • 2011-02-13
    • 2013-05-31
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多