Send Attachment Fields to Email as Attachments (1 Viewer)

cdoner

Registered User.
Local time
Yesterday, 16:45
Joined
Dec 1, 2013
Messages
25
Requesting assistant with getting files (could be zero, 1 or more) from attachment field in MS Access to attach to an email in MS Outlook.

I have tried using code examples from the following two posts below which seem to have a combination of what I'm trying to achieve:
1. Sending Attachment fields to Email as Attachment
2. VBA code to save attachments in specific folder

My code is as follows:
Code:
Option Compare Database
Option Explicit
Public Sub SaveAttachment()
'Funtion to Save Attachments from tblEmailTemplates to include with MS Outlook Email on btnSendEmail below


    Dim db As DAO.Database
    Dim rst As DAO.Recordset2
    Dim rstAttachment As DAO.Recordset2
    Dim fld As DAO.Field2
    Dim strPath As String
        
    Set db = CurrentDb
    Set rst = db.OpenRecordset("tblEmailTemplates", dbOpenDynaset)
        rst.FindFirst "EmailID = " & Me!EmailID
    Set rstAttachment = rst.Fields("EmailAttachments").Value
    Set fld = rstAttachment.Fields("Filedata")
    
    strPath = CurrentProject.Path & "\Attach\" & rstAttachment.Fields("Filename")
    
    On Error Resume Next
    Kill strPath & "\Attach\"
    On Error GoTo 0
    
    fld.SaveToFile strPath 'runtime error '-2147024893 (80070003)'
                                    '<Unknown Error-message> HRESULT: &H800700003
    
    rstAttachment.Close
    rst.Close
    Set rstAttachment = Nothing
    Set rst = Nothing
    Set db = Nothing
    
End Sub

Private Sub btnSendEmail_Click()
'EVERYTHING WORKING EXCEPT ATTACHMENT
'REFERENCE HAD BEEN MADE TO OBJECT LIBRARY.  VBA>Tools>Reference>MS OUTLOOK

    Dim outlookApp As Outlook.Application
    Dim outlookNameSpace As NameSpace 'what is this for?
    Dim objMailItem As MailItem
    Dim objFolder As MAPIFolder 'what is this for?
    Dim strAttachmentPath As String
    Dim rst As DAO.Recordset2
    Dim rstAttachment As DAO.Recordset2
    Dim db As DAO.Database
    
    Dim Salutation As String
    Dim Signature As String
    
'CALL FUNCTION SaveAttachment from above
    Set outlookApp = CreateObject("Outlook.Application")
    Set outlookNameSpace = outlookApp.GetNamespace("mapi")
    Set objFolder = outlookNameSpace.GetDefaultFolder(olFolderInbox)
    Set objMailItem = objFolder.Items.Add(olMailItem)
        
        Set db = CurrentDb
        Set rst = db.OpenRecordset("tblEmailTemplates", dbOpenDynaset)
            rst.FindFirst "EmailID = " & Me!EmailID
        Set rstAttachment = rst.Fields("EmailAttachments").Value
            'rstAttachment Path = CurrentProject.Path & "\Attach\" & rstAttachment.Fields("Filename")
    
'BUILD THE EMAIL TO BE SENT...
'SALUTATION
    Salutation = Me.txtContactFirstName.Value & ","
    
    With objMailItem
    .Display
    End With
    Signature = objMailItem.HTMLBody
       
    objMailItem.To = Nz(Me.txtEmailTo.Value, "")
    objMailItem.CC = Nz(txtEmailCC.Value, "")
    objMailItem.BCC = Nz(txtEmailBCC.Value, "")
    objMailItem.Subject = Nz(Me.txtEmailSubject.Value, "")
    objMailItem.HTMLBody = Salutation & Me.txtEmailBody & Signature

'GRAB ATTACHMENTS FOR EMAIL IF THERE ARE ANY
    If rstAttachment.RecordCount > 0 Then
        Call SaveAttachment
        strAttachmentPath = CurrentProject.Path & "\Attach\" & rstAttachment.Fields("Filename")
    objMailItem.Attachments.Add (strAttachmentPath)
    End If    
    
    With objMailItem
      If Not IsNull(.To) And Not IsNull(.Subject) And Not IsNull(.Body) Then
            .Display
        Else
            MsgBox "Please fill out required fields."
        End If
    End With

'CLOSE FORM
    DoCmd.Close acForm, "frmTestEmail", acSaveNo    
    
End Sub
 

theDBguy

I’m here to help
Staff member
Local time
Yesterday, 16:45
Joined
Oct 29, 2018
Messages
21,447
Hi. You're correct. They each have the things you need; namely, SaveToFile and Attachments.Add. It might be easier though if you could post a test database with sample data, so we can help you put it together.
 

cdoner

Registered User.
Local time
Yesterday, 16:45
Joined
Dec 1, 2013
Messages
25
Sample dB attached. Revised code below. Made some minor changes to field names and formatting for easier reading.

Code:
Option Compare Database
Option Explicit

Function SaveAttachment()
'Funtion to Save Attachments from tblEmailTemplates to include with MS Outlook Email on btnSendEmail below

    Dim db As DAO.Database
    Dim rst As DAO.Recordset2
    Dim rstAttachment As DAO.Recordset2
    Dim fld As DAO.Field2
    Dim strPath As String
        
    Set db = CurrentDb
    Set rst = db.OpenRecordset("tblEmailTemplates", dbOpenDynaset)
        rst.FindFirst "EmailID = " & Me!EmailID
    Set rstAttachment = rst.Fields("EmailAttachments").Value
    Set fld = rstAttachment.Fields("Filedata")
    
    strPath = CurrentProject.Path & "\Attach\" & rstAttachment.Fields("Filename")
    
    On Error Resume Next
    Kill strPath & "\Attach\"
    On Error GoTo 0
    
    fld.SaveToFile strPath
    
    rstAttachment.Close
    rst.Close
    Set rstAttachment = Nothing
    Set rst = Nothing
    Set db = Nothing
End Function


Private Sub cmdSendEmail_Click()
'testing my first vba code to send email with information from MS Access to MS Outlook
'MAKE REFERENCE TO OBJECT LIBRARY.  VBA>Tools>Reference>MS OUTLOOK

    Dim outlookApp As Outlook.Application
    Dim outlookNameSpace As NameSpace 'what is this for?
    Dim objMailItem As MailItem
    Dim objFolder As MAPIFolder 'what is this for?
    Dim strAttachmentPath As String
    Dim rst As DAO.Recordset2
    Dim rstAttachment As DAO.Recordset2
    Dim db As DAO.Database
    
    
    Dim Signature As String
    
'CALL FUNCTION SaveAttachment from above
    Set outlookApp = CreateObject("Outlook.Application")
    Set outlookNameSpace = outlookApp.GetNamespace("mapi")
    Set objFolder = outlookNameSpace.GetDefaultFolder(olFolderInbox)
    Set objMailItem = objFolder.Items.Add(olMailItem)
        
        Set db = CurrentDb
        Set rst = db.OpenRecordset("tblEmailTemplates", dbOpenDynaset)
            rst.FindFirst "EmailID = " & Me!EmailID
        Set rstAttachment = rst.Fields("EmailAttachments").Value
            'rstAttachment Path = CurrentProject.Path & "\Attach\" & rstAttachment.Fields("Filename")
    
'BUILD THE EMAIL TO BE SENT...
    With objMailItem
    .Display
    End With
    Signature = objMailItem.HTMLBody
       
    objMailItem.To = Nz(EmailTo.Value, "")
    objMailItem.CC = Nz(EmailCC.Value, "")
    'objMailItem.BCC = Nz(EmailBCC.Value, "")
    objMailItem.Subject = Nz(EmailSubject.Value, "")
    objMailItem.HTMLBody = EmailBody & Signature

'GRAB ATTACHMENTS FOR EMAIL IF THERE ARE ANY
    If rstAttachment.RecordCount > 0 Then
        Call SaveAttachment
        strAttachmentPath = CurrentProject.Path & "\Attach\" & rstAttachment.Fields("Filename")
    objMailItem.Attachments.Add (strAttachmentPath)
    End If
    
    With objMailItem
      If Not IsNull(.To) And Not IsNull(.Subject) And Not IsNull(.Body) Then
            .Display
        Else
            MsgBox "Please fill out required fields."
        End If
    End With
End Sub
 

Attachments

  • testEmailAttachment dB.zip
    52.9 KB · Views: 461

cdoner

Registered User.
Local time
Yesterday, 16:45
Joined
Dec 1, 2013
Messages
25
I posted a sample dB yesterday. What's a reasonable time for moderator approval? Is there a way for a new user to confirm a post pending review?
 

theDBguy

I’m here to help
Staff member
Local time
Yesterday, 16:45
Joined
Oct 29, 2018
Messages
21,447
I posted a sample dB yesterday. What's a reasonable time for moderator approval? Is there a way for a new user to confirm a post pending review?
From what I understand, mods don't get a notification when a post needs to be approved. The recommended user action is to report one of your previous posts to alert the mods that you have a post waiting to be approved.
 

isladogs

MVP / VIP
Local time
Today, 00:45
Joined
Jan 14, 2017
Messages
18,209
As DBG said, moderators do not get alerted when a post is moderated. So it depends how quickly one of us notices. However we are alerted if you report a post.
Anyway I've now approved it and I'm sure someone will look at it shortly.
Posting this to trigger email notifications
 

cdoner

Registered User.
Local time
Yesterday, 16:45
Joined
Dec 1, 2013
Messages
25
isladogs - Very much appreciated.
 

isladogs

MVP / VIP
Local time
Today, 00:45
Joined
Jan 14, 2017
Messages
18,209
You're welcome. Now you've reached 10+ posts its unlikely posts will be moderated again...but, if they are, you know what to do. :D
 

theDBguy

I’m here to help
Staff member
Local time
Yesterday, 16:45
Joined
Oct 29, 2018
Messages
21,447
Sample dB attached.
Hi. Looking at your demo now. Unfortunately, I don't have Outlook installed at home, so I can't do any testing. It looks like you made an attempt to use both techniques. What happened with your modified code? I am guessing it's still not working, but what exactly is it doing or not doing? Are you getting an error somewhere?


Just to make sure I'm clear, if I'm going to make any changes to the demo, the goal is to click the Send Email button, and an email should be composed for the current record where "all" the attachments are included, correct?
 

cdoner

Registered User.
Local time
Yesterday, 16:45
Joined
Dec 1, 2013
Messages
25
isladogs - Thanks again.

theDBguy -
the goal is to click the Send Email button, and an email should be composed for the current record where "all" the attachments are included, correct?
Correct. The code will successfully produce an email in MS Outlook, it will not attach the files in the attachment field. The code was only changed to account for the field names in the sample dB provided. I receive the same run time error at the same place in the code here.

Code:
fld.SaveToFile strPath 'runtime error '-2147024893 (80070003)'
                                    '<Unknown Error-message> HRESULT: &H800700003

From what I can tell, it looks like the code is correctly locating file path and file name but doesn't appear to execute the attachment of the file to the email.
 

Gasman

Enthusiastic Amateur
Local time
Today, 00:45
Joined
Sep 21, 2011
Messages
14,218
It looks lilke you do not have the attach folder created.?

I commented out the Kill but still got your error.
I created an attach folder and now it works as it should.?

So test for the folder, and if not present, create it, then save it.?

I used this link https://docs.microsoft.com/en-us/of...tabase-reference/field2-savetofile-method-dao and the second example and this is my modified code, as this was all new to me, so I tried to keep it as per the sample.?

HNT
Code:
Function SaveAttachment()
'Funtion to Save Attachments from tblEmailTemplates to include with MS Outlook Email on btnSendEmail below
'Reference www.access-programmers.co.uk/forums/showthread.php?t=245085

    Dim db As DAO.Database
    Dim rst As DAO.Recordset2
    Dim rstA As DAO.Recordset2
    Dim fld As DAO.Field2
    Dim strPath As String
        
    Set db = CurrentDb
    Set rst = db.OpenRecordset("tblEmailTemplates", dbOpenDynaset)
    rst.FindFirst "EmailID = " & Me!EmailID
    Set fld = rst("EmailAttachments")
    Set rstA = fld.Value
    
    strPath = CurrentProject.Path & "\Attach\" & rstA("Filename")
    
    On Error Resume Next
    'Kill strPath & "\Attach\"
    On Error GoTo 0
    
    rstA("FileData").SaveToFile strPath
    
    rstA.Close
    rst.Close
    Set rstA = Nothing
    Set rst = Nothing
    Set db = Nothing
End Function
 

Gasman

Enthusiastic Amateur
Local time
Today, 00:45
Joined
Sep 21, 2011
Messages
14,218
I just unzipped your db again and added the attach folder.

Your code now works as it should. :D

EDit: Fails second time around as file exists, so you only need

Code:
Kill strPath
to allow the save again

HTH
 

cdoner

Registered User.
Local time
Yesterday, 16:45
Joined
Dec 1, 2013
Messages
25
Gasman - Thank you for chiming in. I gave your code a go and get the same run time error but oddly enough on the code segment here:
Code:
rstA("FileData").SaveToFile strPath

However the link you provided seems to be promising. I'll dive into that more and try to digest it. And just to confirm, you were able to get the attachment to automatically attach to the email? If so then maybe the issue resides with a user setting on my side.

Two new things to mention:
1. I've seen in other posts that you must allow for programmatic access in MS Outlook when attempting this feature. It's unclear to me if that is preventing the code from working properly.
2. Another observation I have notice is the record count of the attachment field. At this portion of the code if there are no attachments it correctly displays 0 for record count. If one, it correctly displays 1. However if more than one attachment exists for that particular record the record count displays just 1 (seems to see just the first one in the file and then moves on). This suggests that I will need to have a loop to capture instances of more than one file in the attachment field.
Code:
If rstAttachment.RecordCount > 0 Then
 

Gasman

Enthusiastic Amateur
Local time
Today, 00:45
Joined
Sep 21, 2011
Messages
14,218
You need that Attach folder!! It does not exist. Create that, change the Kill statement and it works, time and time again. :)
 

theDBguy

I’m here to help
Staff member
Local time
Yesterday, 16:45
Joined
Oct 29, 2018
Messages
21,447
Hi cdoner. It looks like you and Gasman have been busy while I was taking a nap (just kidding, I was actually in my corner modifying your file). For what it's worth, I am posting it here. Just as a reminder, I couldn't test it because I don't have Outlook installed, so you'll have to tell us what happens. If it doesn't work, then I guess you can just continue on with what Gasman gave you because he said that one already works. Cheers.
 

Attachments

  • test dB.zip
    45.4 KB · Views: 458

Gasman

Enthusiastic Amateur
Local time
Today, 00:45
Joined
Sep 21, 2011
Messages
14,218
@theDBguy,

The o/p code works except for the fact the Attach folder does not exist, which causes that huge number error and the Kill should only address the strPath as that now contains the full pathname.

He was 99% there with what he had. :D
 

theDBguy

I’m here to help
Staff member
Local time
Yesterday, 16:45
Joined
Oct 29, 2018
Messages
21,447
I see. Thanks, Gas!
 

cdoner

Registered User.
Local time
Yesterday, 16:45
Joined
Dec 1, 2013
Messages
25
@thDBguy - The attached dB you have provided is working like a charm on my side. I'm thoroughly impressed and even more grateful for the assistance. Thank you. Let's call this solved with excellent satisfaction.

@Gasman - 4209 Posts and thanked 742 (make that 743) times and listed as an Enthusiastic Amateur??? You need a promotion partner! Thank you for taking time out of your day to help.
 

Gasman

Enthusiastic Amateur
Local time
Today, 00:45
Joined
Sep 21, 2011
Messages
14,218
Well I am glad it is working for you, as I downloaded it to see another way and mine falls over on

Code:
.To = Me.EmailTo

with Method 'To' of object '_MailItem' failed :banghead:
 

theDBguy

I’m here to help
Staff member
Local time
Yesterday, 16:45
Joined
Oct 29, 2018
Messages
21,447
@thDBguy - The attached dB you have provided is working like a charm on my side. I'm thoroughly impressed and even more grateful for the assistance. Thank you. Let's call this solved with excellent satisfaction.

@Gasman - 4209 Posts and thanked 742 (make that 743) times and listed as an Enthusiastic Amateur??? You need a promotion partner! Thank you for taking time out of your day to help.
Hi. Hope it helps with your actual project. Good luck!
 

Users who are viewing this thread

Top Bottom