ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Attach files to email without storing on disk using ASP.Net FileUpload Control
Author Name: Mudassar Khan Published Date: February 15, 2009
Filed Under :
C#.Net
 |
VB.Net
Views: 4962

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)

If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

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.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code