【问题标题】:How do I get the text part only from Mailman email?如何仅从 Mailman 电子邮件中获取文本部分?
【发布时间】:2012-05-16 04:43:59
【问题描述】:

我正在使用 Mailman gem 来处理我的 Rails 应用程序的传入电子邮件。我的应用程序在纯文本电子邮件中查找 YAML 文档,然后将其加载到 Ruby 对象中以供应用程序进一步操作。

但是,我希望能够提前为可能会使用多部分电子邮件进行响应的电子邮件客户端进行计划。我需要获取电子邮件的纯文本部分并将其传递给 YAML 解析器。

由于某种原因,它在解析 YAML 时仍然存在问题。我猜是因为这里并没有真正得到纯文本部分。

有没有更好的方法来使用 Mailman 获取电子邮件的文本/纯文本部分?我应该放弃 Mailman 并使用 ActionMailer 来代替它吗?

Mailman::Application.run do
    default do
        begin
            message.parts.each do |part|
                Mailman.logger.info part.content_type
                if part.content_type == 'text/plain; charset=ISO-8859-1' # My poor way of getting the text part
                    the_yaml = part.body.decoded.scan(/(\-\-\-.*\.\.\.)/m).first.last # Find the YAML doc in the email and assign it to the_yaml
                    ruby_obj = YAML::load(the_yaml.sub(">", "")) # Remove any >'s automatically added by email clients

                    if ruby_obj['Jackpots']
                        ruby_obj['Jackpots'].each do |jackpot|
                            jp = Jackpot.find(jackpot['jackpot']['id'])
                            jp.prize = jackpot['jackpot']['prize']
                            jp.save
                        end
                    end
                end
            end
        rescue Exception => e
                Mailman.logger.error "Exception occurred while receiving message:\n#{message}"
                Mailman.logger.error [e, *e.backtrace].join("\n")
        end
    end
end

【问题讨论】:

    标签: ruby-on-rails ruby gem mailman-gem


    【解决方案1】:

    我能够找到更好的方法来处理获取电子邮件的文本部分。

    Mailman::Application.run do
        default do
            begin           
                if message.multipart?
                    the_message = message.text_part.body.decoded
                else
                    the_message = message.body.decoded
                end
    
                the_yaml = the_message.sub(">", "").scan(/(\-\-\-.*\.\.\.)/m).first.last
                ruby_obj = YAML::load(the_yaml)
    
                if ruby_obj['Jackpots']
                    ruby_obj['Jackpots'].each do |jackpot|
                        jp = Jackpot.find(jackpot['jackpot']['id'])
                        jp.prize = jackpot['jackpot']['prize']
                        jp.save
                    end
                end
    
            rescue Exception => e
                    Mailman.logger.error "Exception occurred while receiving message:\n#{message}"
                    Mailman.logger.error [e, *e.backtrace].join("\n")
            end
        end
    end
    

    然后通过调试器运行它并在成功解析文本部分后进行检查。它会挂断 YAML 加载。原来,我的几行太长了,电子邮件客户端插入了一个换行符,破坏了我的 YAML 中的评论,从而破坏了整个 YAML 文档。

    【讨论】:

      猜你喜欢
      • 2011-04-09
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 2011-04-15
      • 2015-12-11
      • 2012-05-27
      • 2015-09-19
      • 1970-01-01
      相关资源
      最近更新 更多