Skip to content

Instantly share code, notes, and snippets.

@idiotandrobot
Last active March 6, 2018 03:20
Show Gist options
  • Save idiotandrobot/21fc665e652ffd53a81f to your computer and use it in GitHub Desktop.
Save idiotandrobot/21fc665e652ffd53a81f to your computer and use it in GitHub Desktop.
Office 2016 document emailing macro
Sub EmailDocument()
'On Error Resume Next
If Len(ActiveDocument.Path) = 0 Then
ActiveDocument.Save
End If
Dim RanOutlook As Boolean
Dim Outlook As Object 'Outlook.Application throws "Compile error: User-defined type not defined"
Set Outlook = GetObject(, "Outlook.Application")
If Err <> 0 Then
Set Outlook = CreateObject("Outlook.Application")
RanOutlook = True
End If
Dim DocumentName As String
DocumentName = Left(ActiveDocument.Name, InStr(ActiveDocument.Name, ".") - 1)
Dim Body As String
Body = "<span>Please find " & DocumentName & " attached.<p/>Regards,</span>"
Dim SignatureFile As String
SignatureFile = Environ("appdata") & "\Microsoft\Signatures\Signature.htm"
Dim Signature As String
If Dir(SignatureFile) <> "" Then
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim ts As Object
Set ts = fso.GetFile(SignatureFile).OpenAsTextStream(1, -2)
Signature = ts.readall
ts.Close
Else
Signature = ""
End If
Dim MailItem As Object 'Outlook.MailItem throws "Compile error: User-defined type not defined"
Set MailItem = Outlook.CreateItem(olMailItem)
With MailItem
.Subject = StatementName
.HTMLBody = Body & "" & Signature
'.Attachments.Add Source:=ActiveDocument.FullName, Type:=olByValue fails to add attachement
.Attachments.Add ActiveDocument.FullName
.Display
End With
If RanOutlook Then
Outlook.Quit
End If
Set MailItem = Nothing
Set Outlook = Nothing
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment