Ruby Email to Database Log Script

This is a quick and dirty Ruby script that I threw together years ago to parse emails and jam their contents, line by line, into a MySQL database. It was originally written to handle NetGear firewall logs hence some of the nomenclature.  Very simple but it did the job quite well.  I’m posting it here as someone asked for an example implementation of doing this and I just found this sitting in the code repo.  The key variables are blanked out, just fill them in as needed.  This uses IMAP to connect to the mail server so be sure that IMAP is available.

#!/usr/bin/ruby -w
#Netgear Log IMAP Connector by Scott Alan Miller, 0.3
require 'net/imap'
require 'mysql' 

# Connection Details
usessl      = true
certs       = nil
verify      = false
port        = "993"
server	    = ''
uname	    = ''
pass	    = ''
mbox	    = 'INBOX'
bbox	    = 'TRASH'
db_server   = ""
db_user     = ""
db_pass     = ""
db_name     = ""
subsearch   = ""

# Query Constructors
queryheader = "INSERT INTO events (date_received, subject, details) VALUES ('"
querypiece  = "', '"
queryfooter = "')"

system("echo [nglogger] $(date) Starting >> /var/log/nglogger.log")
imap = Net::IMAP.new(server, port, usessl, certs, verify)
imap.login(uname, pass)
#imap.examine(mbox)
imap.select(mbox)

system("echo [nglogger] $(date) Processing #{ imap.responses["EXISTS"]} Messages >> /var/log/nglogger.log")

# Process IMAP to MySQL Logging
dbsession = Mysql.real_connect(db_server, db_user, db_pass, db_name) # Create MySQL Connection
imap.search(["SINCE", "17-Jan-2008"]).each do |message_id|
	envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
	msg = imap.fetch(message_id, "(UID RFC822.SIZE ENVELOPE BODY[TEXT])")[0]
	msgBody = msg.attr["BODY[TEXT]"]

   	msgBody.chomp!();
   	msgBody.split(/\n/).each do |msgLine|
		msgLine.chomp!();
                if msgLine != "" && msgLine != "End of Log ----------" && msgLine != nil
			msgLine.gsub!(/\'/, "")  # Remove single quotes from SQL Insert
			query = queryheader + envelope.date + querypiece + envelope.subject + querypiece + msgLine + queryfooter
			dbsession.query(query)
     		end
   	end
	imap.copy(message_id, bbox)  # Copy to Processed Folder
	imap.store(message_id, "+FLAGS", [:Deleted])
end
imap.expunge
system("echo [nglogger] $(date) Exiting After IMAP Expunge >> /var/log/nglogger.log")

June 11, 2010: One Million SpiceHeads Party

I was pretty exhausted when the alarm went off at five thirty this morning.  I did not want to get out of bed at all.  I slowly got up and took a shower.  Then I napped on the floor for fifteen minutes before actually dragging myself out the door.   I had tried logging in to the office from home but there was some problem with my workstation so I was unable to get in.  I had some info that I needed before getting on to the road so I drove over to the office and logged in there and worked for a little bit, restarted my workstation and printed out the info that I needed.  Then it was on to the road to drive down to Austin.

I discovered just about immediately that my work BlackBerry was not working so I was not able to send or receive any emails.  Great.  So much for working from the road.  I also had a long conference call this morning but they never opened the conference bridge so that was a waste as well.  I had expected to have been able to have worked from the car while driving for that call since really I am just listening in and not actually participating in any significant way.

The drive down went fine until I needed the GPS in North Austin.  The BMW GPS, which is pretty useless at the best of times, is completely worthless in Austin.  It never knew what road I was on and kept trying to turn me into businesses rather than on roads.  It kept confusing the highway with the side roads and often would send me into nowhere.  We are so not impressed with BMW’s ability to make a guidance system.

It was around ten when I arrived at the SpiceWorks offices on the northwest side of Austin.  The party officially was to start at noon so I was a bit early.  The plan was that I was going to set up and work from the offices there.  I had my laptop and everything.  But the guest wireless system was not set up so I was really screwed – no computer, no BlackBerry and, just to make things worse, no cell service.  I knew that there was no phone service – we learned that the last time that we were here and Dominica was not able to reach us all afternoon.

So that was not a good start to the day at all.  Now I am out of commission all day and I need to get both my desktop and my BlackBerry fixed on Monday.  Argh.

The party was a lot of fun.  There was tons of food and I got interviewed on the live webcast.  Several people emailed me within seconds of seeing me on the webcast.  It was just a quick five minute interview about having won the Innovator of the Year award last year and what it meant to hit one million users, etc.  I also got interviewed by the camera crew for a documentary that they are doing.  No idea when that will be produced.  That was pretty cool.  That was like a real television shoot, more or less.  Lots of ligths, real cameras, a director, an interviewer, I was mic’d, etc.

I left Austin around six and drove back up to Irving.  I was after nine when I finally got back home.  I logged in to the office and worked until after midnight.  Getting done what I could.  At least I get to sleep in tomorrow so it isn’t so bad.  I’m going to be doing a lot of work over the weekend to make up for having lost so much time today.

Dominica, Francesca and the kids arrived in Frankfort around five.  The drive went pretty well for them today.  They are very tired now.

June 10, 2010: Bachelhood Begins

Dominica woke me up around five this morning to take Liesl and Oreo away.  Oreo was all snugly too, like he knew that he was leaving me.  I gave Liesl a kiss goodbye and they were out the door to get on to the road.  They have a lot of driving to do with a lot of people crammed into that vehicle.  I have a lot more driving to do than they do but their mileage is much, much harder.  They have to make a lot of stops with Clara being so young and neither Liesl nor Garrett is going to put up with all that much.  Plus they have Oreo too – who is a very good traveler but still.

I got up just a few minutes after they left and got ready for work and headed on into the office bright and early.  It is time to start being productive.  I really need to take advantage of this time while they are gone so that I can get caught up on all of the stuff that I need to do.  It is more rare for me to have so much time in which I have nothing to do but to work.  Can’t waste it!  It is going to be ten days before I see them again or maybe more.  We haven’t figured out the logistics of how we are meeting once I get the Ralstons up to New York.  I don’t even know where they are going to be at that point.  Neither they nor I have a car once we get to New York which is going to make a lot of things very, very difficult.  It is pretty silly that we are all driving up there with two cars and yet we have no car!

Work was okay.  I spent much of the day today writing Python which is a very nice change from the usual.  I have not actually worked in Python before.  I’ve written a hello world program and I’ve read books on Python and I’ve worked in many related languages like Perl, Ruby, etc.  So this is fun.  We are now using Python for Linux administration at the office – mostly because it is one of only two languages that are really options because they are the two that are installed on every box and it won out over the other, Perl, because it tends to result in code that is readable by anyone needing to verify or modify it whereas the Perl that we get, even from system administrators, tends to border on having been obfuscated.

For lunch today, Nicki and I went to La Cima.  I drove to work today anticipating a La Cima run.  The weather was great today, though, so I am sorry that I did not get a chance to walk instead.  I’m hoping that I can force myself to work this coming week even though I have the car all to myself.  It will be tempting to just drive myself everywhere.

Work was fine this afternoon.  I got regular emails from Dominica letting me know where they were and how the drive was going.  Liesl is having a really rough time of it which is pretty much making it a rough time for everyone.  Francesca has been driving all day but Dominica has at least managed to not fall asleep which is very helpful.  Nothing harder than trying to drive and stay awake while your passenger is nodding off.

I worked till normal time then Nicki and I went over to La Cima for drinks.  We ended up getting dinner there, in the lounge, while we were there.  It was completely packed tonight.  We couldn’t even get to the bar there were so many people.  That was rather surprising.  They cleared out on the early side and we were there till around nine thirty.

I was fairly productive tonight.  Got a lot done.  I was hoping to get to bed around eleven or maybe even earlier but ended up working until around two thirty in the morning!  So much for getting a lot of sleep tonight.  That isn’t going to be good.

Dominica and Francesca made it to Florence, Kentucky tonight.  They are staying there and heading off to New York first thing in the morning.  They made it most of the way and Dominica never had to drive at all so tomorrow is going to be relatively easy for them.  Northern Kentucky to Frankfort is really not a bad drive at all.

I have to be up quite early tomorrow, around five thirty.  I am driving down to Austin for the one million users party at SpiceWorks.  I am going to be on their live webcast and one of the other community members who I know from the online community flew down from Milwaukee tonight for the party so I will get to see him tomorrow.

June 9, 2010: The Grices Visit Irving

Francesca and the kids left Houston around five thirty this morning to drive up to Irving.  It is about a five hour drive and she was trying to get out of Houston before rush hour really began because that could easily tack one to two hours onto the drive time.

It was cooler this morning but extremely humid.  Major storms hitting to the south and east of us plus another major storm system pounding the central midwest around Iowa and Nebraska.  Francesca got stuck driving in horrible storms all day long.  We only got a few minutes of drops in Irving today so I was still able to just walk into the office.

The Grices arrived around ten thirty.  Dominica spent the morning trying to get the house ready.  I came home from work and they were all in the pool.  It was very overcast and threatening to rain so there was no one else out there at all.

I walked over to Jersey Mike’s and picked up subs for everyone for lunch and walked back to the pool where we ate.  Still, the heat isn’t too bad but the humidity is just crazy today.  While we were eating a few sprinkles started to come down so we hurriedly packed up and went back up to the apartment.

I had to deal with our credit card being turned off over lunch today.  We travel so much and do so much online shopping that we are constantly setting off the alarms with the banks.  What a pain that is.  I explained that Dominica would be traveling for the next several days so they hopefully will not turn it off on her while she is out on the road.

I walked back to work, risking the rain.  It was a busy afternoon at work but I managed to get home at six so that we could get ready to go to La Cima.  Our dinner reservations were for six thirty but we were not able to get everyone ready in time for that.  We arrived around seven.

Liesl is now officially used to the club.  We got into the elevator and she said “Cima, Cima!”  She said it again when we walked into the club.

Dinner was insanely hectic.  It did not occur to us that we should have gotten a private room with so many people – we had enough to fill some of the rooms to capacity!  So we were in the main dining room at a huge table.

Dinner, with so many people, ended up taking way too long and Liesl just could not stand it. She was so ancy from the very beginning and by the time that we had our main courses we were walking her around trying to keep her occupied and before I could finish I had to take her down to the ground floor lobby and play with her there as she had decided to start screaming.  It was just too much for her having family visiting and swimming for a while, only getting a short nap then having a really long dinner at La Cima.  A private room would have made all of the difference.

It was quite late by the time that we got home from the club and all we did was feed Oreo, walk him and try to get everyone off to bed.  That took forever, though, and Liesl would just not fall asleep.  It was around midnight before we were able to get to sleep which is going to be awful tomorrow as everyone has to get up at four thirty in the morning so that they can get on to the road to get driving to New York!

Their plan is not to make it all of the way tomorrow but just to go as far as they can before night and then get a hotel and go the rest of the way on Friday.

June 8, 2010: Date Night

Did well at getting into work at a decent time this morning.  I’m working hard to get up early in the morning and get out the door.  I was doing well then started getting out of the habit for a while there.  I really have to get in early or else it is so hot that I just can’t stand it.  It is getting to be crazy hot here in Texas.  We are already into temperatures to which I am not accustomed.

Work was insanely busy today.  Very little time to think at all.  I walked home for lunch today – it was quite warm but somehow it never seems to be as bad when going home for lunch as it is coming into the office early in the morning.  I wonder if it might be a lot more humid first thing in the morning or something?

The plan for this evening was to go to La Cima to use our free meal vouchers for the month of June because tonight is the last opportunity to use them at all.  So we made seven o’clock reservations.  I also made reservations for tomorrow night at La Cima to take the Grices to pasta night.

I tried to get out of work early but that did not work out at all.  Instead of making it away early I ended up getting stuck quite late.  I called Dominica and had her pick me up from work to save time.  I did not manage to get out until around seven thirty which was quite late for getting over to the club.

We got over to the club and had an awesome dinner, even if it was late and Liesl was way past her time to start winding down for the night.  We had our huge four course dinners plus a side of mac and cheese that was amazing.  Maybe the best that I have ever had.  Instead of swordfish they had lemon crusted halibut which we both ended up getting.  I didn’t like it as much as the swordfish but it was good.

Liesl was getting fussy so we grabbed our desserts and made a dash to get home.  That worked fairly well.  We were still pushing our luck but she was decently happy.

Tonight was our last night alone.  The Grices are arriving from Houston tomorrow morning.