I am attempting to include a .pdf document as an email attachment. The following is the code that I am using:
I am passing in the location of the file in the following format: C:\mylog\templates\supportdocument.pdf
However when I try to attach the file I get a System.Net.Mail.Smtpexception that tells me "Failure sending mail" with the inner message being: "Cannot access a closed file"
Any suggestions? I have checked and have the necessary permissions, Im sure. Sometimes, the code also seems to corrupt the file as when I try to open the file I get the message: "Adobe Reader could not open supportDocument.pdf because it is either not a supported file type or because the file has been damaged (it was sent as an email attachment + wasnt correctly decoded)"
Michael.
Code:
Dim smtpClient As New SmtpClient
Dim message As New MailMessage
SendEmail = True
Try
Gets the SMTP Email credentials
If GetEmailAccountDetails(emailSmtp, emailUser, emailPass) = True Then
Dim fromAddress As MailAddress = New MailAddress(sender)
Dim smtpAuthentication As New System.Net.NetworkCredential(emailUser, emailPass)
Sets the smptclient properties
smtpClient.Host = emailSmtp
smtpClient.UseDefaultCredentials = False
Sets the smpt port and Authentication
smtpClient.Port = 25
smtpClient.Credentials = smtpAuthentication
Set Message
message.From = fromAddress
message.To.Add(receipient)
message.Subject = subject
message.IsBodyHtml = True
message.Body = messageBody
Sets the Attachement if required
If Len(mailAttachment) <> 0 And System.IO.File.Exists(mailAttachment) = True Then
Dim fileAttached As New System.Net.Mail.Attachment(mailAttachment)
message.Attachments.Add(fileAttached)
fileAttached.Dispose()
End If
If Len(mailAttachment2) <> 0 And System.IO.File.Exists(mailAttachment2) = True Then
Dim fileAttached As New System.Net.Mail.Attachment(mailAttachment2)
message.Attachments.Add(fileAttached)
fileAttached.Dispose()
End If
Sends the message
smtpClient.Send(message)
Else
Return False
End If
Catch ex As Exception
Return False
Finally
End Try
I am passing in the location of the file in the following format: C:\mylog\templates\supportdocument.pdf
However when I try to attach the file I get a System.Net.Mail.Smtpexception that tells me "Failure sending mail" with the inner message being: "Cannot access a closed file"
Any suggestions? I have checked and have the necessary permissions, Im sure. Sometimes, the code also seems to corrupt the file as when I try to open the file I get the message: "Adobe Reader could not open supportDocument.pdf because it is either not a supported file type or because the file has been damaged (it was sent as an email attachment + wasnt correctly decoded)"
Michael.