2012-05-16 32 views
1

我正在使用Mailman gem來處理我的Rails應用程序的傳入電子郵件。我的應用程序在純文本電子郵件中查找YAML文檔,然後將其加載到Ruby對象中以供應用程序進一步操作。如何僅從郵件電子郵件中獲取文本部分?

但是,我希望能夠提前計劃可能會用多部分電子郵件回覆的電子郵件客戶端。我需要獲取電子郵件的純文本部分並將其傳遞到YAML分析器。

由於某些原因,解析YAML時仍然存在問題。我猜是因爲這裏並沒有真正獲得純文本部分。

有沒有更好的方法來獲得郵件的文本/純文本部分?我是否應該取消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 

回答

2

我能找到一個更好的方式來處理獲取電子郵件的文本部分。

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文檔。

相關問題