Share via

VBA code for send e-mail button

Anonymous
2011-08-24T17:37:12+00:00

Hello,

I'm trying to find some Word VBA code that I can use to send an active document as an e-mail attachment.

  • I will attach it to a button
  • We're using Windows 7 and Office 2010

Can anyone help me?

Thanks

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

HansV 462.6K Reputation points
2011-08-26T14:28:49+00:00

Although the methods and properties for routing slips are still present in Word VBA, they cannot be used any more starting with Word 2007.

Try this instead:

Sub Test()

    Options.SendMailAttach = True

    ActiveWindow.EnvelopeVisible = True

    With ActiveDocument.MailEnvelope.Item

        .Subject = "Testing 123"

        .Recipients.Add "******@somewhere.com"

    End With

End Sub

Was this answer helpful?

0 comments No comments

18 additional answers

Sort by: Most helpful
  1. Anonymous
    2016-12-10T06:35:45+00:00

    This is an old thread, so I thought it worth updating my earlier code.

    The document is always saved in order to attach it, but it is difficult to reproduce your requirement as the SendMail option requires some user interaction. To avoid that you can create a process that will do so. The following code should go in the form template (saved as a macro enabled template), and it will need the Function to open Outlook from Ben Clothier - http://www.rondebruin.nl/win/s1/outlook/openclose.htm for reasons discussed there. The following code calls that function so will crash without it.

    Create a new document from the template and complete it.

    The main macro uses a function I developed to send documents by mail, in a variety of ways, but you only need to send the document as an attachment, so that function called from the first macro. That macro saves the document to a temporary location, attaches the temporary document to the message, and sends it to the named address, with the message body and subject placed in the message. The default signature associated with the sending account is included.

    The document is then closed and the user offered the opportunity to create a new document.

    Option Explicit

    Sub SendDoc()

    'Graham Mayor - http://www.gmayor.com - Last updated - 10/12/2016

    Const strMsg As String = "Please find the enclosed document" 'the message body text

    Const strRecipient As String = "someoneATsomewhere.com" 'the e-mail address of the intended recipient

    Const strSubject As String = "Attached Form" 'the message subject

    Dim sPath As String

        sPath = Environ("TEMP") & "\Form Document.docx" 'the temporary filename

        ActiveDocument.SaveAs2 FileName:=sPath, AddToRecentFiles:=False

        Send_As_Mail strRecipient, strSubject, strMsg, True

        ActiveDocument.Close 0

        If MsgBox("Create another form?", vbYesNo) = vbYes Then

            Documents.Add Template:=ThisDocument.FullName

        End If

    lbl_Exit:

        Exit Sub

    End Sub

    Public Sub Send_As_Mail(strTo As String, _

                            strSubject As String, _

                            strMessage As String, _

                            Optional bSendAsAttachment As Boolean, _

                            Optional bPDFFormat As Boolean, _

                            Optional strAttachment As String)

    'Graham Mayor - http://www.gmayor.com - Last updated - 10/12/2016

    'bSendAsAttachment - Enter True/False - indicate whether to send the active document as an attachment

    'Requires the code by Ben Clothier - http://www.rondebruin.nl/win/s1/outlook/openclose.htm

    'to either retrieve an open instance of Outlook or open Outlook if it is closed.

    Dim olApp As Object

    Dim olInsp As Object

    Dim oItem As Object

    Dim wdDoc As Object

    Dim oRng As Object

    Dim bStarted As Boolean

    Dim oDoc As Document

    Dim strDocName As String

    Dim strPath As String

    Dim intPos As Integer

    Dim iFormat As Long

        Set oDoc = ActiveDocument

        If Not bSendAsAttachment Then oDoc.Range.Copy

        If bSendAsAttachment Then

            'On Error GoTo Err_Handler

            'Prompt the user to save the document

            If bPDFFormat Then

                strDocName = oDoc.Name

                strPath = oDoc.Path & ""

                intPos = InStrRev(strDocName, ".")

                strDocName = Left(strDocName, intPos - 1)

                strDocName = strPath & strDocName & ".pdf"

                oDoc.ExportAsFixedFormat OutputFilename:=strDocName, _

                                         ExportFormat:=wdExportFormatPDF, _

                                         OpenAfterExport:=False, _

                                         OptimizeFor:=wdExportOptimizeForPrint, _

                                         Range:=wdExportAllDocument, From:=1, to:=1, _

                                         Item:=wdExportDocumentContent, _

                                         IncludeDocProps:=True, _

                                         KeepIRM:=True, _

                                         CreateBookmarks:=wdExportCreateHeadingBookmarks, _

                                         DocStructureTags:=True, _

                                         BitmapMissingFonts:=True, _

                                         UseISO19005_1:=False

            Else

                strDocName = oDoc.FullName

            End If

        End If

        Set olApp = OutlookApp()

        'Create a new mailitem

        Set oItem = olApp.CreateItem(0)

        With oItem

            .to = strTo

            .Subject = strSubject

            If bSendAsAttachment Then .Attachments.Add strDocName

            If Not strAttachment = "" Then .Attachments.Add strAttachment

            .BodyFormat = 2        'olFormatHTML

            Set olInsp = .GetInspector

            Set wdDoc = olInsp.WordEditor

            Set oRng = wdDoc.Range(0, 0)

            .Display

            If bSendAsAttachment Then

                oRng.Text = strMessage & vbCr

            Else

                oRng.Paste

            End If

            '.Send        'restore after testing

        End With

        If bStarted Then olApp.Quit

    lbl_Exit:

        Set oItem = Nothing

        Set olApp = Nothing

        Set olInsp = Nothing

        Set wdDoc = Nothing

        Set oDoc = Nothing

        Set oRng = Nothing

        Exit Sub

    err_handler:

        Err.Clear

        GoTo lbl_Exit

    End Sub

    Was this answer helpful?

    0 comments No comments
  2. Doug Robbins - MVP - Office Apps and Services 323.1K Reputation points MVP Volunteer Moderator
    2016-12-09T22:59:58+00:00

    Did you look at Ken Puls information?

    However, here is some code that should do it.  

    Option Explicit

    Dim strAddress As String

    Dim strSubject As String

    Dim strMessage As String

    Dim strAttach As String

    Dim bStarted As Boolean

    Dim oOutlookApp As Object

    Dim oItem As Object

    Sub Mailit()

    On Error GoTo ErrMsg

    strAddress = InputBox("Insert the e-mail address")

    strSubject = InputBox("Insert the Subject")

    strMessage = InputBox("Insert the text for the message")

    On Error Resume Next

    Set oOutlookApp = GetObject(, "Outlook.Application")

    If Err <> 0 Then

        Set oOutlookApp = CreateObject("Outlook.Application")

        bStarted = True

    End If

    On Error GoTo ErrMsg

    ActiveDocument.SaveAs strFolder & MergeData(k, fname), fileformat:=wdFormatDocumentDefault, AddtoRecentFiles:=False

    strAttach = ActiveDocument.FullName

    Set oItem = oOutlookApp.CreateItem(0)

    With oItem

        .To = strAddress

        .subject = strSubject

        .Body = strMessage

        .Attachments.Add strAttach

        .Send

    End With

    Set oItem = Nothing

    ActiveDocument.Close wdDoNotSaveChanges

    Set oOutlookApp = Nothing

    '  Close Outlook if it was started by this macro.

    If bStarted Then

        oOutlookApp.Quit

    End If

    ErrMsg:

        If Err.Number <> 0 And Err.Number <> 91 Then

            MsgBox Err.Number & vbCr & Err.Description

        End If

    End Sub

    Note that there are numerous other ways to get the email address, subject and message text, in which case, you would replace the InputBoxes with the applicable code.  To send an document as an attachment, it is necessary to be able to specify the field name so that it can be attached and thus it is necessary to save the document.

    Was this answer helpful?

    0 comments No comments
  3. Anonymous
    2016-12-09T22:08:08+00:00

    Hi Doug.  Wow, thanks for the quick response!

    We're an 'Office365' shop, so we use Outlook as the email client.

    I'd like the document sent as an attachment.

    It would be nifty if the document didn't need to be 'saved' before being sent.  (this is a form in a template, so I'd like if they could just fill out the form, and hit the button to send it)

    The subject and the email address would be hard-coded into the VB for that button's click-event.

    The

    Options.SendMailAttach = True

    ActiveDocument.SendMail

    part works fine.  But doesn't include the subject or recipient, which means the users would have to change those to the appropriate values.

    Just trying to both save the users steps, and keep them sending the filled-in-form to the wrong place!

    jk

    Was this answer helpful?

    0 comments No comments
  4. Doug Robbins - MVP - Office Apps and Services 323.1K Reputation points MVP Volunteer Moderator
    2016-12-09T21:56:26+00:00

    What e-mail application are you using?

    Do you want the document sent as the body of an email message, or as an attachment?

    From where would the code get the Subject and the recipient's e-mail address?

    See Ken Puls Emailing with VBA at:

    http://www.excelguru.ca/content.php?249-Easy-Outlook-Email-Integration#comments\_start

    Was this answer helpful?

    0 comments No comments