EmailDatabaseObject "Multiple Reports"

Posted on 2012-03-16
Last Modified: 2012-03-23
I have this code within a module that emails specific reports to client. The code calls a function that opens up Outlook, calls a wait function and waits 20 seconds for Outlook to send/receive. It then sends an email with one report, waits 3 seconds, then another, and another, and Outlook does an automatic send/receive before exiting. The problem is all these emails are going to the same person.

What I would like to do is make it so that all three reports, are sent in the same email. I have tried various combinations of the code and they all fail. This is the code that sends the emails:

    WaitSeconds (20)
    DoCmd.SendObject acReport, "CustStmt", "PDFFormat(*.pdf)", "", "", "", "CustStmt", "", False, ""

    WaitSeconds (3)

    DoCmd.SendObject acReport, "CustAdjmts", "PDFFormat(*.pdf)", "", "", "", "CustAdjmts", "", False, ""

    WaitSeconds (3)

    DoCmd.SendObject acReport, "CustStmt Summary (Roche)", "PDFFormat(*.pdf)", "", "", "", "CustStmt Summary (Roche)", "", False, ""

Any help would be greatly appreciated
Question by:dawber39
LVL 57
ID: 37729777
SendObject simply can't do that, so you'll need to find another way to send e-mails.  There are a couple of basic methods:

1. Use a command line utility such as BLAT.

2. Use software that talks directly to a e-mail server (SMTP) such as vbSendMail

3. Using OLE automation, talk to Outlook and have it send the e-mail.

 All three of the above will allow for multiple attachments in a single e-mail.  However with that said, that's the other piece of this; you need to run and save the reports to disk first in some format (PDF, Snapshot, etc) before you can send as a single e-mail.

LVL 57
ID: 37729785
You might also want to consider commercial software, such as FMS, inc's Total Access Mailer.

LVL 74

Expert Comment

by:Jeffrey Coachman
ID: 37729870
Not sure, but you may be able to do this is you instantiate Outlook, using this fairly common code:

You would probably need to change the top to this:

    Sub SendMessage(DisplayMsg As Boolean)

...and change the "Add Attachment" section to something like this:
             ' Add attachments to the message.
                      Set objOutlookAttach = .Attachments.Add(AttachmentPath1)
                      Set objOutlookAttach = .Attachments.Add(AttachmentPath2)
                      Set objOutlookAttach = .Attachments.Add(AttachmentPath3)

(I am not quite sure why your "Delays" are needed though...)

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

LVL 26

Accepted Solution

Nick67 earned 500 total points
ID: 37730008
If you can create the pdf's to a folder, this code will email them'
Option Compare Database
Option Explicit

Public Sub CreateAnEmail(reportcaption As String, ClientEmail As String, AttachmentPath As String)
'reportcaption is a semicolon delimited string of report file names, without file extensions
'eg "rptReport1;rptReport2"
'ClientEmail is a semicolon delimited string of recipients
'eg ";"
'AttachmentPath is a sting pointing to where your PDFs are
'eg "C:\temp"

On Error GoTo myerr
Dim DisplayMsg As Boolean
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Dim objOutlookExplorers As Outlook.Explorers
Dim myarray() As String
Dim myaddresses() As String
Dim x As Integer
Dim fs As Object
Dim BuiltPath As String
Dim response As Integer
Dim wasOpen As Boolean

myarray = Split(reportcaption, ";")
'MsgBox UBound(MyArray, 1)

DisplayMsg = True
'AttachmentPath = "c:\temp\" & ReportCaption & ".pdf"

MsgBox "The email is about to be created!" & vbCrLf & _
        "If nothing appears to be happening, the Outlook security box may be hiding behind an open window." & vbCrLf & _
        "Click the Outlook icon on the taskbar to bring it to the front, if necessary."

Set objOutlook = GetObject(, "Outlook.Application")
'MsgBox Err.Number & " " & Err.Description
If Err.Number = 429 Then
    wasOpen = False
    ' Create the Outlook session.
    Set objOutlook = CreateObject("Outlook.Application")
    wasOpen = True
End If
    Dim ns As Outlook.NameSpace
    Dim Folder As Outlook.MAPIFolder
    Set ns = objOutlook.GetNamespace("MAPI")
    Set Folder = ns.GetDefaultFolder(olFolderInbox)
    Set objOutlookExplorers = objOutlook.Explorers
If wasOpen = False Then
    objOutlook.Explorers.Add Folder
    'done opening
End If

AppActivate "Microsoft Outlook"

' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)

'Who at Baker Oil Tools gets the email depends on Location/Cost Code

With objOutlookMsg
    If Not ClientEmail Like "*@*" Then
        MsgBox "You haven't supplied a valid email!"
        Exit Sub
    End If
    If Nz(ClientEmail, "") <> "" Then
    ' Add the To recipient(s) to the message.
    myaddresses = Split(ClientEmail, ";")
    For x = LBound(myaddresses) To UBound(myaddresses)
        Set objOutlookRecip = .Recipients.Add(myaddresses(x))
        objOutlookRecip.Type = olTo
    Next x
    End If

    'can't do this, the mail never gets sent
    ' Add the from recipient(s) to the message.
    'Set objOutlookRecip = .Recipients.Add("")
    'objOutlookRecip.Type = olOriginator
    ' Add the CC recipient(s) to the message.
    'Set objOutlookRecip = .Recipients.Add("")
    'objOutlookRecip.Type = olCC

   ' Add the BCC recipient(s) to the message.
    'Set objOutlookRecip = .Recipients.Add("""")
    'objOutlookRecip.Type = olBCC

   ' Set the Subject, Body, and Importance of the message.
         .Subject = "Requested reports " & IIf(Len(reportcaption) < 161, reportcaption, Left(reportcaption, 159) & "...")

   .Body = "This is an automated sending by XXXXXXXXXXX as requested." & vbCrLf & vbCrLf & _
   "Please respond to with any inquiries"
   ' Add attachments to the message.
   'reportcaption is passed in and split into myarray
   'one attachment needs to be added for each element in myarray

    For x = LBound(myarray, 1) To UBound(myarray, 1)
        AttachmentPath = AttachmentPath & "\" & myarray(x) & ".pdf"
        If Not IsMissing(AttachmentPath) Then
            Set objOutlookAttach = .Attachments.Add(AttachmentPath)
            MsgBox "The attachment was not found or attached!"
        End If
    Next x
   ' Resolve each Recipient's name.
   For Each objOutlookRecip In .Recipients

   ' Should we display the message before sending?
   If DisplayMsg Then
   End If
End With

Set objOutlook = Nothing

Exit Sub
    If Err.Number = 5 Then
Resume Next
    MsgBox Err.Number & " " & Err.Description & " occurred.  exiting!"
End If

End Sub

Open in new window

Working sample attached.
Note that a reference to the Microsoft Outlook 1x.0 Object Library is required
(11.0 for Access 2003, 12.0 for Access 2007, 14.0 for Access 2010)
LVL 26

Expert Comment

ID: 37730870
I cleaned that up from working code and tested it.
There are, looking at now, some extraneous declarations and comments in it
LVL 10

Expert Comment

by:Luke Chung
ID: 37732561
Hi Jim, Thanks for mentioning Total Access Emailer:

It is a Microsoft Access add-in that lets you automatically attach multiple filtered reports as PDF to a message. You can also compress all your attachments into a zip file. The zip file can also be password protected using your phrase or a value from a field in your datasource.

Total Access Emailer also has a programmatic interface to send emails from VBA. A free trial version is available. It uses SMTP to send emails, so it bypasses all the Outlook and MAPI security limitations. Free trial here:

Here's a paper we wrote entitled: DoCmd SendObject Command in Microsoft Access: Features and Limitations for Sending Emails

Author Closing Comment

ID: 37758693
Haven't tried it yet - but the sample works - had shoulder surgery, and everything is on hold for now - thank you all

Featured Post

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction The Visual Basic for Applications (VBA) language is at the heart of every application that you write. It is your key to taking Access beyond the world of wizards into a world where anything is possible. This article introduces you to…
A simple tool to export all objects of two Access files as text and compare it with Meld, a free diff tool.
Familiarize people with the process of utilizing SQL Server views from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Access…
With Microsoft Access, learn how to start a database in different ways and produce different start-up actions allowing you to use a single database to perform multiple tasks. Specify a start-up form through options: Specify an Autoexec macro: Us…

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question