Sometimes there is a requirement to download the attachments of mails being accessed thorugh IMAP protocol in Rails.
1. Firstly, we need to connect to imap and login to the mail account of the user.
def get_messages require 'net/imap' require 'mail' imap = Net::IMAP.new(params[:host], params[:port], params[:ssl]) imap.login(params[:username], params[:password])
2. Then we need to select the folder from where we will download the attachments.
imap.select(params[:folder])
3. Then we can loop through all the mails in that folder and can save the attachments on our end as depicted below.
imap.search('ALL').each do |message_id| body = imap.fetch(message_id, 'RFC822')[0].attr['RFC822'] mail = Mail.new(body) unless mail.attachments.blank? unless File.exists?("public/attachments/#{mail.message_id}") Dir.mkdir(File.join("public/attachments", "#{mail.message_id}"), 0700) end mail.attachments.each do |attachment| File.open("public/attachments/#{mail.message_id}/#{attachment.filename}", 'wb') do |file| file.write(attachment.body.decoded) end end end imap.logout imap.disconnect end