« Return to Thread: How to Create Records in Rails App Database using Inbound Email including Image File Attachments

Re: How to Create Records in Rails App Database using Inbound Email including Image File Attachments

by Jamey Cribbs-3 :: Rate this Message:

Reply to Author | View in Thread


Nathan wrote:
> I am trying to create a feature within my application to receive
> product data including an image attachment via inbound email.
>
> Can someone point me to a tutorial or other document online that will
> help out with this.  I have started hammering at Google, but was
> hoping someone could provide a link.
>  

Here's some code I use in one of my apps.  Stole most of it from some
examples I found somewhere, don't remember where:


class IncomingCSVFileHandler < ActionMailer::Base
  def receive(email)
    return unless email.has_attachments?

    email.attachments.each do |attachment|
      next unless attachment.original_filename[-4..-1] == '.csv'

      CSV::Reader.parse(attachment.read) do |rec|
        next if rec.last.blank?
        server = Server.find_by_name(rec.last.split('-',
2).first.strip.upcase)
        next if server.blank?

        a = Answer.new
        a.server = server
        a.ticket_no = rec.first
        a.question = rec[2]
        a.answer = rec.last.split(' - ', 2).last
        first_name, last_name = rec[3].split
        a.created_by = User.find_by_name("#{last_name},
#{first_name}.titleize")
        a.last_updated = Time.now
        a.updated_by = a.created_by
        a.save!
        RAILS_DEFAULT_LOGGER.info("Added answer record for #{server.name}")
      end
    end
  end

  def self.check_mail
    begin
      imap = Net::IMAP.new('130.102.202.121')
      imap.login('userid', 'password')
      imap.select('remedycsvfiles')
      imap.search(["SINCE", Date.today.strftime("%d-%b-%Y")]
       ).each do |message_id|
        msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']

        IncomingCSVFileHandler.receive(msg)

        #Mark message as deleted and it will be removed from storage
when user
        #session closed
#        imap.store(message_id, "+FLAGS", [:Deleted])
      end
#      imap.expunge
      imap.logout
    rescue
      RAILS_DEFAULT_LOGGER.error("Remedy CSV File Import Error: " + $!)
    end
  end
end


Not pretty, but it works!

HTH,

Jamey Cribbs






--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@...
To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe@...
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

 « Return to Thread: How to Create Records in Rails App Database using Inbound Email including Image File Attachments