VBA script to convert emails via markdown

Jared Martin martin.jared at gmail.com
Thu Sep 12 12:48:15 EDT 2013

I hate Microsoft's GUI interface, and I love Markdown (I am an active
stackoverflow user). But for work, I have to use Outlook. So I thought,
well, maybe I can write emails in Markdown, and use VBA to convert them.

This almost works, actually. The problem is that markdown doesn't create
paragraphs the way Office wants them, when encoding the raw body text.
Below is the VBA script I wrote... feel free to adapt and use, if you can
figure out how to fix the paragraphing problem... but if you do, let me
know! Note also that you should add a reference to the "Microsoft Scripting
Runtime" in Tools -> References.

Thanks in advance,

Option Explicit

Public Declare PtrSafe Sub Sleep Lib "kernel32" ( _
ByVal dwMilliseconds As LongLong)

Private Const pathToPerl = "C:\your\path\to\perl.exe"
Private Const pathToScript = "C:\your\path\to\Markdown.pl"
Private Const tempFileName = "\markdown.text"

Sub Markdown()
Dim myItem As MailItem
Dim tempAbsolutePath As String
Dim position As Long, endPosition As Long
Dim prefix As String, converted As String

'get currently active email
If (Not Application.activeInspector.IsWordMail) Then Exit Sub
Set myItem = Application.activeInspector.CurrentItem

If (Not myItem.BodyFormat = olFormatHTML) Then
myItem.BodyFormat = olFormatHTML
End If

position = InStr(1, myItem.HTMLBody, "<BODY", vbTextCompare)
endPosition = InStr(position, myItem.HTMLBody, ">", vbTextCompare)
prefix = Left$(myItem.HTMLBody, endPosition)

' Store the in progress email in a temp file
tempFileAbsolutePath = IIf(Environ$("tmp") <> "", Environ$("tmp"),
Environ$("temp")) & tempFileName

Open tempAbsolutePath For Output As #1
Print #1, myItem.Body
Close #1

converted = ConvertFile(tempAbsolutePath)
myItem.HTMLBody = prefix & converted & "</body></html>"
End Sub

Private Function ConvertFile(emailFile As String)
Dim oWsc As Object
Set oWsc = CreateObject("WScript.Shell")
Dim oExec As Object
Dim execCommand As String
execCommand = pathToPerl & " " & pathToScript & " " & emailFile

Set oExec = oWsc.Exec(execCommand)
While oExec.Status <> 1 ' Wait for process
Sleep 100
ConvertFile = oExec.StdOut.ReadAll()
Set oWsc = Nothing
Set oExec = Nothing
End Function
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://six.pairlist.net/pipermail/markdown-discuss/attachments/20130912/81c7f44d/attachment.html>

More information about the Markdown-Discuss mailing list