Search code examples
ruby-on-rails-3emailincoming-mailmailman-gem

how to process incoming mails using mailman and update them into the database


am developing ruby on rails3 application where i am sending an email to user and if user replies that email then that reply content, date should be updated to the database. For this i have ProductComment model. when admin sends comment to the user it will be stored in the database. if user replies to that then database should be updated accordingly. I am trying to use mailman. I have installed the gem. But am not getting how to get the comment id, what should i write in replyto address, where to write the mailman code and from which mail i should read.

Am sending email like this:

mail(:to => @user.email, :subject => "Edit Your Product", :reply_to=>"[email protected])

I am handling it in products controller like this:

require 'mailman'
Mailman::Application.run do
to '[email protected]' do
ProductComment.create(message)
end
end

Please help me to come out from this problem

Please tell me how to use mailman gem in ruby on rails3 application


Solution

  • there is a recent pro-episode on receiving emails with mailman on railscasts: http://railscasts.com/episodes/313-receiving-email-with-mailman

    chmod +x script/mailman_server
    cat mailman_test.eml | script/mailman_server
    script/mailman_server
    

    -

    # script/mailman_server
    #!/usr/bin/env ruby
    require "rubygems"
    require "bundler/setup"
    require "mailman"
    
    Mailman.config.logger = Logger.new("log/mailman.log")
    
    Mailman.config.pop3 = {
      server: 'pop.gmail.com', port: 995, ssl: true,
      username: ENV["GMAIL_USERNAME"],
      password: ENV["GMAIL_PASSWORD"]
    }
    
    Mailman::Application.run do
      default do
        begin
          Ticket.receive_mail(message)
        rescue Exception => e
          Mailman.logger.error "Exception occurred while receiving message:\n#{message}"
          Mailman.logger.error [e, *e.backtrace].join("\n")
        end
      end
    end
    

    -

    def self.receive_mail(message)
      ticket_id = message.subject[/^Update (\d+)$/, 1]
      if ticket_id.present? && Ticket.exists?(ticket_id)
        Ticket.update(ticket_id, body: message.body.decoded)
      else
        Ticket.create subject: message.subject, body: message.body.decoded, from: message.from.first
      end
    end