Dvolution

Adding e-mail attachment using FileUpload

I recently had the need to have a user fill in a form that would be e-mailed to an administrator. The user had the option to attach a file to the e-mail using a FileUpload control, but I never really figured out how to attach that to the MailMessage object. I was always thinking that you had to do this the complicated way using streams and other sorts of methods, but it turns out it can be quite easy to accomplish using the piece of code below. The filUpload variable is the FileUpload control and the msg variable is an instance of the MailMessage class. Hopefully it can be of help to someone!

If filUpload.HasFile Then
   Dim path As String = Path.GetFileName(filUpload.PostedFile.FileName)
   Dim att As New Attachment(filUpload.FileContent, path)
   msg.Attachments.Add(att)
End If
Steven is een afgestudeerd Software Engineer en heeft een baan als .NET ontwikkelaar. Fan van wielrennen, doet zelf aan mountainbiken, speelt wanneer hij zin heeft op zijn gitaar en Xbox 360. Probeert met enige regelmaat te bloggen over vanalles en nog niets.

2 reacties op “Adding e-mail attachment using FileUpload”

  1. This might come in quite handy for the website I’m making. It’s for a course in which at the end the students have to send in an excel sheet.

    Keep on finding good stuff like this

  2. Finally came to the point where I wanted to use this code. Turned out a bit different but the result is the same.

    Found that using streams is actually quite easy:

    msg.Attachments.Add(New Net.Mail.Attachment(FileUpload1.PostedFile.InputStream, AttFile)

    AttFile is a custom string based on a students number and name and results in a file name.

Ik heb iets te zeggen!

Adding e-mail attachment using FileUpload