Definitive Source for Code to Automate E-Mailing Forms

You will find that at some point you need to be a little more clever with sending mail than what InfoPath will allow you to do with just the GUI and dataconnections.  A colleague of mine, Scott Heim, sent me an awesome little XSN file that had 4 buttons in it that highlighting four different ways to kick off e-mail programmatically from InfoPath.   If you e-mail me I'll send you the file.  The code however is pretty easy to follow and is posted here for your enjoyment.


Sub btnShowMailItem_OnClick(eventObj)

XDocument.UI.ShowMailItem "", "", "", "Subject: Test", "Body: Test"

End Sub '

Sub btnMailEnvelope_OnClick(eventObj)

Dim oEnvelope

Set oEnvelope = Application.ActiveWindow.MailEnvelope

oEnvelope.Subject = "Subject: Test"

oEnvelope.To =

oEnvelope.Visible = true

End Sub

Sub btnOutlook_OnClick(eventObj)

Dim objOutlook

Dim objOutlookMsg

Dim objOutlookRecip

Dim objOutlookAttach

Dim frmSavePath

'Create the Outlook session.

Set objOutlook = CreateObject("Outlook.Application")

Set objOutlookMsg = objOutlook.CreateItem(0) 'olMailItem

With objOutlookMsg

'Add the To recipient(s) to the message.

Set objOutlookRecip = .Recipients.Add(

objOutlookRecip.Type = 1 'olTo '

'Add the CC recipient(s) to the message.

' Set objOutlookRecip = .Recipients.Add(

' objOutlookRecip.Type = 2 'olCC '

' 'Add the BCC recipient(s) to the message.

' Set objOutlookRecip = .Recipients.Add(

' objOutlookRecip.Type = 3 'olBCC

'Set the Subject, Body, and Importance of the message.

.Subject = "This is an Automation test with Microsoft Outlook"

.body = "This is the body of the message"

' **NOTE: if you want the body of the message to be HTML, then use '.HTMLbody instead of just .body

.Importance = 2 'High importance

'Resolve each Recipient's name.

For Each objOutlookRecip In .Recipients



'Display the message before sending


'If you want to add the form as an attachment, you need to make sure it is saved first and then add that file as an attachment


frmSavePath = "C:\MyForm.XML"


Set objOutlookAttach = .Attachments.Add(frmSavePath)

End With

Set objOutlook = Nothing

Set objOutlookMsg = Nothing

Set objOutlookRecip = Nothing

Set objOutlookAttach = Nothing

End Sub