I have the following code which is run after a report is exported to a pdf file which should attach the report to an email with a pre-defined body and automatically send to the correct recipient based on a query. I am getting a run-time error 2147467259 "There must be at least one name or contact group in the To, Cc, or Bcc box. I am fairly certain this is because the recordset appears empty when it is opened, but I cannot understand why. If I run the query (SELECT RECIPIENT FROM qry_Sales_IDI_Email WHERE INVOICE = Forms!frm_Sales!INVOICE
independently, then I get the expected resulting RECIPIENT email address.
Code:
Public Function Send_Sales_IDI_EMail()
Dim db As DAO.Database
Dim MailList As DAO.Recordset
Dim MyOutlook As Outlook.Application
Dim MyMail As Outlook.MailItem
Dim Subjectline As String
Dim BodyFile As String
Dim fso As FileSystemObject
Dim MyBody As TextStream
Dim MyBodyText As String
FileID = Forms!frm_Sales!INVOICE
mysql = "SELECT RECIPIENT FROM qry_Sales_IDI_Email WHERE INVOICE = " & FileID & ";"
myattach = "\\MSTFPS004\Finance\" & FileID & ".pdf"
Set fso = New FileSystemObject
Subjectline$ = "Sales IDI " & FileID
If Subjectline$ = "" Then
MsgBox "No subject line, no message." & vbNewLine & vbNewLine & _
"Quitting...", vbCritical, "E-Mail Merger"
Exit Function
End If
BodyFile$ = "\\MSTFPS004\Finance\IDIEMailBody.txt"
If BodyFile$ = "" Then
MsgBox "No body, no message." & vbNewLine & vbNewLine & _
"Quitting...", vbCritical, "I Ain't Got No-Body!"
Exit Function
End If
If fso.FileExists(BodyFile$) = False Then
MsgBox "The body file isn't where you say it is. " & vbNewLine & vbNewLine & _
"Quitting...", vbCritical, "I Ain't Got No-Body!"
Exit Function
End If
Set MyBody = fso.OpenTextFile(BodyFile, ForReading, False, TristateUseDefault)
MyBodyText = MyBody.ReadAll
MyBody.Close
Set MyOutlook = New Outlook.Application
Set db = CurrentDb()
Set MailList = db.OpenRecordset(MySQL)
Set MyMail = MyOutlook.CreateItem(olMailItem)
Do Until MailList.EOF
MyMail.Recipients.Add MailList("RECIPIENT")
MailList.MoveNext
Loop
MyMail.Subject = Subjectline$
MyMail.Body = MyBodyText
MyMail.Attachments.Add myattach, olByValue, , "Sales IDI"
MyMail.Send
Set MyMail = Nothing
Set MyOutlook = Nothing
MailList.Close
Set MailList = Nothing
db.Close
Set db = Nothing
End Function
Mod Edit: include CODE tags and fix code more readable