Cant attached printed pdf document as email attachment in VB.net

150 Views Asked by At

I am able to create a pdf document and I can browse the folder and open the document with no issue. But when my code try to attach the file as an attachment then it fails with this error, but the path and filename is correct. I suspect the file is somehow open which prevents the attachment.

Proof of files:

enter image description here

Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll Could not find file 'C:\TEMP\1104280343081_INV0950.pdf'. This part works perfectly

        Dim txtVarFile As String
        Dim txtVarEmail As String = "[email protected]"
        Dim txtVarPasss As String = "password"
        Dim txtVarSMTP As String = "smtp.gmail.com"
        Dim intVarPort As Integer = 587
        Dim txtVarDescription As String

        'Create Invoice and Save as pdf document
        txtVarFile = "C:\TEMP\" & strClientNum & "_" & strInvNum & ".pdf"
        PageSetupDialog1.Document = PrintDocument1
        PageSetupDialog1.PrinterSettings.DefaultPageSettings.Landscape = True
        prtFrmInvoice.PrinterSettings = PageSetupDialog1.PrinterSettings
        If prtFrmInvoice.PrinterSettings.IsValid Then
            prtFrmInvoice.PrinterSettings.PrinterName = "Microsoft Print to PDF"
            prtFrmInvoice.PrintFileName = txtVarFile
            prtFrmInvoice.PrintAction = Printing.PrintAction.PrintToFile
            prtFrmInvoice.Print()
        End If

But this does not work, it tells me the file can not be found, but the file is there Exception is thrown at this line: eMail.From = New MailAddress(txtVarEmail)

'Send copy of Invoice per Email
        Try
            Dim SmtpServer As New SmtpClient()
            Dim eMail As New MailMessage()
            'Dim attachment As System.Net.Mail.Attachment
            LogFile.Refresh()
            SmtpServer.UseDefaultCredentials = False
            SmtpServer.Credentials = New Net.NetworkCredential(txtVarEmail, txtVarPasss)
            SmtpServer.Port = intVarPort
            SmtpServer.EnableSsl = True
            SmtpServer.Host = txtVarSMTP
            eMail = New MailMessage()
            eMail.From = New MailAddress(txtVarEmail)
            eMail.To.Add(strClientEmail)
            eMail.Subject = "AltHealth Invoice"
            eMail.Body = "Please find your latest invoice attached"
            'attachment = New System.Net.Mail.Attachment(txtVarFile)
            'eMail.Attachments.Add(attachment)
            eMail.Attachments.Add(New Attachment(txtVarFile))

            SmtpServer.Send(eMail)
            MsgBox("The Invoice has been sent sucessfully via email - File: " & txtVarFile)
        Catch ex As Exception
            MsgBox("Send failure: " & ex.ToString())
        End Try
0

There are 0 best solutions below