Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require File.expand_path('../../config/environment.rb', __FILE__)
- require 'net/sftp'
- require 'fileutils'
- module MailParser
- def self.sftp_retrieve opts={}
- Net::SFTP.start opts[:server], opts[:username], :password => opts[:password] do |sftp|
- p 'connected'
- i = 0
- sftp.dir.glob opts[:source], "**/*" do |entry|
- server_path = "#{opts[:source]}/#{entry.name}"
- local_path = "#{opts[:target]}/#{entry.name}"
- p server_path
- p local_path
- p "Copying #{entry.name}"
- sftp.download! server_path, local_path
- # p "Deleting #{name}"
- # sftp.remove(server_path)
- yield local_path
- # debug
- break if limit = opts[:limit] and (i += 1) >= limit
- end
- end
- end
- def self.parse file
- result = {}
- mail = Mail.read file
- if mail && mail.multipart?
- result[:bounced_at] = mail.date
- if msg = mail.parts.find { |part| part.content_type =~ /message\/rfc822/i }
- mail2 = Mail.new msg.body
- slug = mail2.reply_to.to_s[/notification\+(.*)@/,1]
- result[:sent_email] = SentEmail[:slug => slug] if slug
- raise SlugNotMatchedError unless result[:sent_email]
- yield result
- end
- end
- end
- class ParseError < StandardError; self; end
- class SlugNotMatchedError < ParseError; self; end
- end
- WORKING_DIR = [:new, :processed, :failed].inject({}) { |hash,dir| hash.merge({dir => "/Users/jeshuaborges/Desktop/test/#{dir}"}) }
- # ensure all working dirs have been created
- WORKING_DIR.values.each { |dir| FileUtils.mkdir dir rescue nil }
- MailParser.sftp_retrieve(
- :server => 'homerunmail.com',
- :username => 'fbl',
- :password => 'h0merun1sc00l',
- :source => "Maildir/new",
- :target => WORKING_DIR[:new],
- :limit => 1
- ) do |local_path|
- begin
- MailParser.parse local_path do |result|
- se = result[:sent_email]
- bounced_at = result[:bounced_at]
- se.feed_back_loop! bounced_at
- FileUtils.mv local_path, WORKING_DIR[:processed]
- end
- rescue MailParser::ParseError
- FileUtils.mv local_path, WORKING_DIR[:failed]
- end
- end
Add Comment
Please, Sign In to add comment