Skip to content

Instantly share code, notes, and snippets.

@vagmi
Created February 16, 2009 12:20
Show Gist options
  • Save vagmi/65141 to your computer and use it in GitHub Desktop.
Save vagmi/65141 to your computer and use it in GitHub Desktop.
'''
outlook.pyw (OutLook editor launcher) -- allows one to edit an open e-mail
mesg from Outlook using Emacs or *Vi* rather than "Notepad--". :-)
NOTE: requires Python 1.6 and newer (use of string methods)
created by John Klassa (klassa at employees.org) on 2001 May 29
updated by Wesley Chun (cyberweb at rocketmail.com) on 2002 Feb 28
$Id: outlook.pyw,v 0.2 2002/08/28 18:04:06 wesc Exp wesc $
'''
from os import spawnv, P_WAIT, unlink
from tempfile import mktemp
from Tkinter import Tk, Button, Frame, Label
from Tkconstants import *
from win32com.client import Dispatch
def launch():
'''launch() spawns your favorite editor to edit the Outlook compose
window (either new or reply), then returns that data to Outlook...
change the 'ed' variable to switch editors.'''
# Get a handle to Outlook.
o = Dispatch("Outlook.Application")
# Work our way down to the reply (a "MailItem").
insp = o.ActiveInspector()
if insp == None: return
item = insp.CurrentItem
if item == None: return
# Grab the message body in the reply.
body = item.Body
# Write the body... need to "encode" the string because Outlook uses
# Unicode with bunch of unprintables (ASCII chars > 128). Also, since
# we are going from DOS2UNIX2DOS, we have the \r\n vs \n issue, re-
# sulting in those fabulous ^M characters. A persistent, bound-to-a-
# key Emacs macro takes care of that nicely, but the solution imple-
# mented here is to just wipe the '\r's now, then add them back when
# we reread this file back before returning the body to Outlook.
tmp = mktemp() # generate a unique tmp filename
fh = open(tmp, "w")
fh.write(body.encode('ascii', 'ignore').replace('\r\n', '\n'))
fh.close()
# Launch editor to edit the file (should make this configurable).
#ed = r"d:\emacs-20.7\bin\emacs" # emacs editor binary
ed = r"c:\tools\vim\vim72\gvim.exe " # *vi* editor binary
spawnv(P_WAIT, ed, [ed, tmp])
# Read edited file back into memory, restore '\r's, and kill tmp file.
fh = open(tmp)
body = fh.read().replace('\n', '\r\n')
fh.close()
unlink(tmp)
# Store it as the body of the reply. Note that we are merely
# sending this data back to Outlook -- it does not prevent MS from
# mucking with your message. For example, it may add your signature
# again, or it may remove newlines. MS software... what can you do?
item.Body = body
# Create the Tk(inter) GUI app with the appropriate label and buttons.
if __name__=='__main__':
tk = Tk()
f = Frame(tk, relief=RIDGE, borderwidth=2).pack()
Label(f, text="Outlook Edit Launcher v0.2").pack()
Button(f, text="Edit", fg='blue', command=launch).pack(fill=BOTH)
Button(f, text="Quit", fg='red', command=tk.quit).pack(fill=BOTH)
tk.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment