Wednesday, August 15, 2007

Using NetWorkSpaces with Python

In order to try out NetWorkSpaces for Python, I tackled a problem I've had for some time.  Due to IT reasons, its easier to have my Outlook client run on a PC nearby, and view that PC through VNC.  But, sometimes I miss meeting notices if I'm not around to hear the reminder sound through the PC's speakers.

First I needed create Macros for Outlook to run each time I received an email or a reminder.  There are subroutines called 'Application_NewMail' and 'Application_Reminder' that are called, so I grabbed some information from the subject in each of those routines, entitled each with either 'Email' or 'Reminder', and sent the info to a Python script:



Public Function SendText1(title, txt)
Dim prog As String
Dim t As String
Dim WSHShell

Set WSHShell = CreateObject("wscript.Shell")
t = " " & Trim(txt)
prog = "c:\Python25\Python.exe c:\Python25\doNotify.py " & title & " """ & t & """"
WSHShell.Run prog, 1, 1
Set WSHShell = Nothing
End Function


Private Sub Application_NewMail()
Dim oFolder
Dim oNewItem
Dim s
Dim n

Set oFolder = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set oNewItem = oFolder.Items.GetLast
Rem For Each oNewItem In oFolder.Items.Restrict("[Unread] = 0")
s = oNewItem.SenderName & ": "
s = s & Trim(oNewItem.Subject)
n = "Email"
Call SendText1(n, s)
Rem Next
End Sub

Private Sub Application_Reminder(ByVal Item As Object)
Dim s As String
Dim sBody As String
Dim n

s = Item.Subject & "(" & Item.Location & ") " & FormatDateTime(Item.Start, vbShortTime)
n = "Reminder"
Call SendText1(n, s)
End Sub


Notice in 'SendText1' I run a Python script called 'doNotify.py' with two parameters, coming in as args[1] and args[2]:



# doNotify.py
from nws.client import NetWorkSpace
import sys

def main(args):
ws = NetWorkSpace('kh_outlook', serverHost='bvt-dc00133', useUse=True)
ws.store('notify', (args[1],args[2]))

if __name__=="__main__":
main(sys.argv)



The script grabs the NetWorkSpace 'kh_outlook', stores to the name 'notify' a tuple for the two arguments, and then exits.

On my Mac, I run a 'server' that hangs around, watching the NetWorkSpace of 'kh_outlook', fetching 'notify', and passing the two strings from the tuple to Growl, using growlnotify:



# outlook_server.py
import os
from nws.client import NetWorkSpace

print "Starting server..."
ws = NetWorkSpace('kh_outlook', serverHost='bvt-dc00133', persistent=True)
try:
while 1:
message = ws.fetch('notify')
cl = "growlnotify -s -a mail.app -m \"" + message[1] + "\" -t " + message[0]
os.system(cl)
except KeyboardInterrupt:
print 'shutting down gracefully.'

print 'Exiting.'



I get Growl messages for each email or reminder, titled ('-t' option) with either 'Email' or 'Reminder' respectively, and I set those messages sticky with the '-s' option so I won't miss them if I'm away from my Mac.

No comments: