清除下一个循环的电子邮件附件

时间:2014-02-26 12:12:45

标签: vba email ms-access email-attachments

我正在尝试使用以下代码将附件发送到电子邮件列表。电子邮件已成功发送,但第二个电子邮件地址将获得附件以及第一个电子邮件地址的附件,因此第三个电子邮件地址将获得第一个和第二个附件。

我的问题是:在附件实际添加之前,有没有办法清除附件?我试着搜索但没有运气。

请指导我,谢谢。

Set rsInvoices = db.OpenRecordset("SELECT * FROM Invoices WHERE InvMonth = " &  Month(dtPeriod) & " AND InvYear = " & Year(dtPeriod))

selectQuery = "SELECT Email FROM Student WHERE ID = "

On Error GoTo CloseReportHandler

If Not (rsInvoices.EOF And rsInvoices.BOF) Then

    Do Until rsInvoices.EOF = True

        DoCmd.OpenReport strReportName, acViewPreview, , "Invoice.SID = " & Chr(34) & rsInvoices!SID & Chr(34) & " AND Invoice.InvYear = " & rsInvoices!InvYear & " AND Invoice.InvMonth = " & rsInvoices!InvMonth

        fileName = "Invoice-" & rsInvoices!SID & "-" & rsInvoices!InvYear & "-" & rsInvoices!InvMonth & ".pdf"

        selectQuery = selectQuery + rsInvoices!SID

        Set rsStudents = db.OpenRecordset("SELECT Email FROM Student WHERE ID = " & Chr(34) & rsInvoices!SID & Chr(34))

        studEmail = rsStudents!Email

        DoCmd.OutputTo acOutputReport, , acFormatPDF, path + fileName, False
        DoCmd.Close acReport, "Invoice"

        With cdomsg
            .To = studEmail
            .From = "xxx@example.com"
            .subject = "Test Email"
            .TextBody = "Hello"
            .AddAttachment path + fileName
            Set .Configuration = cdoconf
            .Send
        End With

  MoveNextInvoice:
        rsInvoices.MoveNext


    Loop

    Set cdomsg = Nothing
End If

 CloseReportHandler:
    Select Case Err
    Case 2501
        'MsgBox ("here")
        Resume MoveNextInvoice
    Case Else
        MsgBox (Err.Description)
    End Select

Set cdomsg = Nothing
'Kill (path + "*.pdf")
rsInvoices.Close
End Sub

1 个答案:

答案 0 :(得分:1)

你可以做以下两件事之一:

  1. .Attachments.DeleteAll语句之前放置.AddAttachment语句,或

  2. Set cdomsg = ...循环内创建CDO.Message对象(Set cdomessage = Nothing),发送它和Do Until,以便为每次迭代使用新的CDO.Message对象