#!/usr/bin/env ruby

# imap msg list to rss feed

require 'rubygems'
require 'net/imap'
require 'rss/maker'

@login='login'
@pass='pass'
@mss= 'imap server'

# max fetched messages
@maxMsgListSize=100

# meaningful link if you want to click and open the message
# you may need to tweak it for your client.
#
@messageLink = "http://webmail/" 

begin
	feedElements = Array.new
	imap = Net::IMAP.new(@mss)
	imap.login(@login, @pass)
	imap.examine('INBOX')
	imapStatus = imap.status("inbox", ["MESSAGES", "RECENT"])

	imap.search(["NEW"]).each do |message_id|
		envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
		sender= (envelope.sender.nil?)?"nil sender":envelope.sender[0].name
		subject = (envelope.subject.nil?)?"nil subject":envelope.subject
		date=(envelope.date.nil?)?"nil date":envelope.date
		elem = {'date'=>date, 'sender'=> sender, 'subject'=>subject, 'msgid'=>message_id}
		feedElements << elem
		break if (feedElements.length==@maxMsgListSize)
	end
	imap.logout

	content = RSS::Maker.make('2.0') do |m|
		m.channel.title = "#{@login}'s INBOX"
		m.channel.link = "http://webmail"
		m.channel.description = "New messages for #{@login} - Messages: #{imapStatus['MESSAGES']} Recent: #{imapStatus['RECENT']}"
		m.items.do_sort = true # sort items by date
		feedElements.each {|elem|
			i = m.items.new_item
			if (elem['subject'] == nil)
				elem['subject']=""
			end
			if (elem['sender'] == nil)
				elem['sender']=""
			end
			title="Subject: "+elem['subject']+" from:"+elem['sender']
			i.title = title
			i.link = @messageLink+" msgid: "+elem['msgid'].to_s
			i.date = Time.parse(elem['date'])
		}
	end

	File.open('messages.xml',"w") do |f|
		f.write(content)
	end

rescue
	puts "Err: "+$!
	puts "Trace:"
	$@.each {|tl|
		puts tl
	}
end
Advertisements
%d bloggers like this: