Attach files to email without storing on disk using ASP.Net FileUpload Control
 
Author:
Filed Under: C#.Net  |  VB.Net
Published Date: Feb 15, 2009
Views: 9177
 

Abstract: Here Mudassar Ahmed Khan has explained how to attach files to email without saving them onto the disk directly from the FileUpload stream

Comments:  3

 

Here’ I’ll explain how to attach files to email without saving them on the disk

You can refer my articles on how to send emails in

Send SMTP Emails using System.Net Class in C#   and Send SMTP Emails using System.Net Class in VB.Net


When the File is uploaded using FileUpload Control the file is received in the httppostedfile

property.


To attach the HttpPostedFile  to the email. You will need to convert it to Stream.

The code below attaches a posted file to email. Note that txtAttachment is  a FileUpload control


<asp:FileUpload ID="txtAttachment" runat="server" />


C#


if (txtAttachment.PostedFile != null)

{

    try

    {

        string strFileName =

        System.IO.Path.GetFileName(txtAttachment.PostedFile.FileName);

        Attachment attachFile =

        new Attachment(txtAttachment.PostedFile.InputStream, strFileName);

        mm.Attachments.Add(attachFile);

    }

    catch

    {

 

    }

}



  VB.Net

If txtAttachment.PostedFile IsNot Nothing Then

  Try

 

    Dim strFileName As String =  System.IO.Path.GetFileName(txtAttachment.PostedFile.FileName)

    Dim attachment As New Attachment(txtAttachment.PostedFile.InputStream,  strFileName)

    mm.Attachments.Add(attachment)

    Catch

 

    End Try

End If


You can download the source code here.

EmailWithAttachment.zip (4.28 kb)








Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit