Sending Attachments Directly From a FileUpload Control

With previous versions of ASP.NET you couldn't attach an uploaded file directly to a mail message. Instead, you needed to save the file to disk, attach it to the mail message and then when sending the message succeeded you had to clean up the old file again.

This not only meant a lot of work, it also had some security implications. Because the file needed to be written to disk, the account used by the web server required write permissions to a folder to store the attachments.

Now, with the new constructors for the Attachment class from the System.Net.Mail namespace, these problems are gone....

Attaching the PostedFile to an E-mail Message

The Attachment class has a constructor that allows you to pass an IO.Stream and a file name. Conveniently, the FileUpload control has a FileContent property that returns the uploaded file as an IO.Stream. All that's left to do is to get the file name from the uploaded file using Path.GetFileName and you're good to go. The code below shows a working example of sending an attachment from an asp:FileUpload control directly. The download at the end of the chapter contains a web site with two pages: working examples of this code in VB.NET and C#. For the code to work, you need to import the System.Net.Mail and System.IO namespaces.

C#
if (FileUpload1.HasFile) { string toAddress = "you@yourprovider.com"; string fromAddress = "you@yourprovider.com"; string mailServer = "smtp.yourprovider.com"; MailMessage myMailMessage = new MailMessage(); myMailMessage.To.Add(toAddress); myMailMessage.From = new MailAddress(fromAddress); myMailMessage.Subject = "Test Message"; string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); Attachment myAttachment = new Attachment(FileUpload1.FileContent, fileName); myMailMessage.Attachments.Add(myAttachment); SmtpClient mySmtpClient = new SmtpClient(mailServer); mySmtpClient.Send(myMailMessage); } VB.NET
If FileUpload1.HasFile Then Dim toAddress As String = "you@yourprovider.com" Dim fromAddress As String = "you@yourprovider.com" Dim mailServer As String = "smtp.yourprovider.com" Dim myMailMessage As MailMessage = New MailMessage() myMailMessage.To.Add(toAddress) myMailMessage.From = New MailAddress(fromAddress) myMailMessage.Subject = "Test Message" Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName) Dim myAttachment As New Attachment(FileUpload1.FileContent, fileName) myMailMessage.Attachments.Add(myAttachment) Dim mySmtpClient As New SmtpClient(mailServer) mySmtpClient.Send(myMailMessage) End If

Download Files

Source Code for this Article

Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Sunday, February 11, 2007 11:03:36 PM Eleonora said:
Hi,

Great article but I have one porblem. When e-mail is sent attached file is empty (to open it with Adobe you get an error saying that an e-mail attachment was not correctly decoded). Any ideas? Will greatly appreciate any feedback.

Thanks
On Wednesday, April 04, 2007 8:17:29 AM Sam said:
I tried this but I'm getting an error. It says that "The name Path doesn't exist in the current context". Can you tell me how to solve this?
On Wednesday, April 04, 2007 8:23:18 AM Imar Spaanjaars said:
Hi Sam,

Hover your mouse over the word Path in Visual Studio. You'll see an error helper that suggests to add a using statement for System.IO.....

If you don't see that, add

using System.IO;

to the top of your code file.

Hope this helps,

Imar
On Wednesday, April 04, 2007 9:11:24 AM Sam said:
Thanks for your help. That solved the problem. I have one more error which says something like "cannot implicitly convert type string to system.net.mailaddress". It seems like a silly little issue but nothing I've tried seems to solve it.
On Monday, July 16, 2007 11:10:17 AM Surj said:
Good one...
On Monday, April 28, 2008 8:11:54 PM Colin said:
Hi Imar

I'm new to asp.net and have downloaded your code for the upload control.  Do you have any more examples of a basic web email contact form which would allow a visitor to provide some details and comments and attach/upload a homework?  I hope that you don't think that I'm being lazy but I've trawled the net for one and everything I find is tied up in master pages and not very clear.  If so I would be very grateful if you could point me in the right direction.  If not thanks for this again.
On Tuesday, April 29, 2008 5:57:11 AM Imar Spaanjaars said:
Hi Colin,

Take a look here: http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=414

I don't understand why Master Pages would complicate things; they usually help to separate things so they are easier to understand. Maybe you don't know how they work? http://msdn2.microsoft.com/en-us/library/ehszf8ax(VS.80).aspx

Cheers,

Imar
On Tuesday, April 29, 2008 4:13:37 PM Colin said:
Thanks Imar.
On Tuesday, June 24, 2008 3:10:31 PM earl said:
when i execute this code the attachment is sent with no problem but the file has no content. any ideas
On Thursday, June 26, 2008 9:39:38 AM Imar Spaanjaars said:
Hi earl,

Sorry, no idea. Try posting this, and the full source code on a forum like http://p2p.wrox.com

Cheers,

Imar
On Thursday, June 26, 2008 1:28:40 PM Earl said:
Hi Imar,

Sorry i didn't update but I did figure out my problem and now it works fine. thanks for the help
On Thursday, May 14, 2009 10:17:28 AM Rob said:
Nice article. Exactly what I was looking for!

Thanks
On Tuesday, September 01, 2009 9:32:47 AM Anu said:
Hi

I m able to send attachment correctly if i send for 1 user.I i send for multiple users right from the 2nd user the Size of the Attachment is Zero.
only for the first user it is sent correctly.Any idea
On Tuesday, September 01, 2009 11:41:33 AM Imar Spaanjaars said:
Hi Anu,

Are you sure your loop code is correct? I just tried this code in a loop and it works just fine.

Cheers,

Imar
On Tuesday, September 01, 2009 11:50:49 AM Anu said:
Hi Imar,

Thanks for the Quick Reply.I m using HTML inputfile Control.But same thing is happening for FileUpload Control also.

SendTo -Will have Email Address to be sent.
Any ideas???PLease help me out

private void SendEmail(string SendTo, string Subject, string Body,ArrayList ALhif)
        {

if (ALhif.Count>0)
                {

                    foreach (System.Web.UI.HtmlControls.HtmlInputFile fu1 in ALhif)
                    {
                        string filename = Path.GetFileName(fu1.PostedFile.FileName);
                        
                        if (fu1.PostedFile.ContentLength>0)
                        {
                            Attachment fileAttach = new Attachment(fu1.PostedFile.InputStream, filename);
                            
                            
                            message.Attachments.Add(fileAttach);
                        }
                        else
                        {
                            smtpClient.Send(message);
                        }
                        
                    }
                    smtpClient.Send(message);
                }

                else
                {
                    smtpClient.Send(message);
                }

                
            }
}

Where ALhif is an Arraylist which will have path of the Files uplload

like this

void btnAdd_Click(object sender, EventArgs e)
        {
            if (Page.IsPostBack == true)
            {
                ALhif.Add(fileFind);//filefind is HTML InputControl
                
                string strfilename = fileFind.PostedFile.FileName;
                if (strfilename != "")
                {
                    lstboxAttachment.Items.Add(strfilename);
                }
            }

          
            
        }
On Tuesday, September 01, 2009 9:04:37 PM Imar Spaanjaars said:
Hi Anu,

Difficult to say without seeing the full code, but it looks like you're trying to upload multiple files in different post backs and then adding them to a list? If that's the case, this won't work. Only files uploaded in the current post are accessible.

If this doesn't help, can you start a new thread at http://p2p.wrox.com/index.php?referrerid=385 It's a bit difficult to share code here on my site.

Cheers,

Imar
On Sunday, October 11, 2009 7:32:36 AM liewen Cheng said:
It seems that the attached file will reside in the server.  Is there any way that the uploaded file will be deleted right after the mail being sent.
On Sunday, October 11, 2009 8:26:57 AM Imar Spaanjaars said:
Hi liewen,

And where would it be stored? The whole idea of this code is that it's *not* stored on disk; this should be an in-memory only operation. Are you seeing different behavior?

Imar
On Tuesday, April 13, 2010 8:20:10 PM Andres Morales said:
Fast and easy like the programming task need to be

thank you
On Friday, August 13, 2010 1:42:56 PM tf said:
perfect!!!!!!!!!!!! thanx :)
On Friday, November 12, 2010 6:34:21 PM vishal said:
thanks for suggestion for sending mail with attachmet its working fine,but i want to upload more files using 2 other file upload control pls help me
On Friday, November 12, 2010 6:53:54 PM Imar Spaanjaars said:
Hi vishal,

Not sure what to help you with; it's exactly the same as my current example, but then for the other controls.

Cheers,

Imar
On Friday, November 12, 2010 7:00:50 PM vishal said:
thanks for reply i want to telling u that im am uising 3 file upload contron in my .aspx page how can i send mail with these 3 attachments pls reply
On Friday, November 12, 2010 7:23:48 PM Imar Spaanjaars said:
Just repeat the code that adds the attachment three times (and move the check that ensures the upload control has a file).

Cheers,

Imar
On Friday, November 12, 2010 7:29:32 PM vishal said:
dear Imar,
                pls write code
On Friday, November 12, 2010 8:13:44 PM Imar Spaanjaars said:
Please write code????? Why don't *you* write some code, try it out and see how far you get? I am not your servant.

And pls is not a word....

Imar
On Sunday, November 14, 2010 6:06:35 PM vishal said:
hi imar
          why u angry on me,u r the best coader so that why u be an angry,so play it cool n i was try to  the code that adds the attachment three times but it was give error so help me to write code
On Monday, November 15, 2010 9:01:02 AM Imar Spaanjaars said:
Hi vishal,

I am not angry. I am just telling you how things are. I am not your servant. And pls is not a word.

If you need help with programming, post your code in an appropriate category on a forum such as this one: http://p2p.wrox.com/index.php?referrerid=385

Also, you may want to consider your spelling when you post something. MSN-speak is likely to be ignored much easier in public forums.

Cheers,

Imar
On Monday, September 12, 2011 3:48:35 AM Geetika said:
Hi Imar,

I am doing the same thing as you mentioned in the code.It's working but the problem is that  the attachment(image) becomes empty.I am not able to understand how it is becoming empty.

I hope you can help

Thanks
On Monday, September 12, 2011 9:23:54 AM Imar Spaanjaars said:
Hi Geetika,

When you debug your code, does FileUpload1 have a file? (E.g. is HasFile true?)

Imar
On Monday, September 12, 2011 10:18:11 AM Geetika said:
Yes Fileupload1 has file,in fact the mail is being sent with the attachment but there is no content in the attachment.I was basically attaching an image (jpg) file.The attachment image.jpg came with the mail but when I opened it ,it was empty.
On Monday, September 12, 2011 1:36:24 PM Imar Spaanjaars said:
Hi Geetika,

Try dropping the e-mail on a local disk as explained here: http://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-delivery

If the e-mail contains an attachment there, the code is OK and something is wrong in the mail server.

Otherwise, I don't know what's going on. This code as-is works fine for me.

Cheers,

Imar
On Thursday, November 01, 2012 12:51:59 PM Dave said:
@earl is actually correct, although I think even he struggled to explain why it's happening!

This behaviour does exist but only under very explicit circumstances.  It has been reported to Microsoft via Connect.

A full example and solution is detailed here:
http://www.codepal.co.uk/show/Sending_Email_Attachments_From_a_FileUpload_Control_Sends_Empty_Files
On Friday, November 02, 2012 10:11:36 AM Imar Spaanjaars said:
Hi Dave,

It could be a bug indeed, or it could be by design. I tried setting the Position of the InputStream to 0 (which should do the trick with seekable streams), but that didn't help either. Copying the data to a MemoryStream as in your second example is probably the best workaround.

Cheers,

Imar
On Friday, November 02, 2012 10:18:17 AM Imar Spaanjaars said:
Think I just found out what the issue is, and I think it's by design.

When you instantiate the attachment, the stream isn't read yet. Only when you send out the message using mc.Send(mm) is the stream read. This means that shortly after that, the stream is at the end and can't be read again. If you reset the stream between the two calls to Send() it should work:

mc.Send(mm)
fu.PostedFile.InputStream.Position = 0
mc.Send(mm2)

Hope this helps,

Imar
On Friday, November 02, 2012 11:22:51 AM Dave said:
Hey Imar
Superb clarification, thanks very much.  That makes sense.
I'll amend my post to account for this information.
Just for my sanity, is there a chance that a stream might not be seekable?  What might cause this?
Cheers,
Dave
On Friday, November 02, 2012 11:32:40 AM Imar Spaanjaars said:
Not all Stream types support seeking (such as a stream returned from WebResponse). However, in your case, the stream does support it, so you can use my code without problems.

Cheers,

Imar
On Friday, November 02, 2012 11:44:02 AM Dave said:
Great work Imar.  Keep up the good work.  I'll be reading your future posts with interest :-)
On Friday, June 28, 2013 8:56:57 AM Dhananjayan said:
very nice
On Tuesday, August 12, 2014 2:36:17 PM kristof said:
Thank you sir!
On Thursday, August 14, 2014 7:53:51 AM Kajsa said:
The code line
fu.PostedFile.InputStream.Position = 0
just saved my day. Thank you Imar!
On Monday, March 02, 2015 7:47:28 AM Devendra said:
we can put the pdf file into access database in vb.net and retrive also.plz. anybody provide me the code.
On Monday, March 02, 2015 11:33:12 PM Imar Spaanjaars said:
Hi there,

You may want to check out this article: http://imar.spaanjaars.com/556/building-a-provider-based-file-storage-system-using-net

Cheers,

Imar
On Tuesday, November 03, 2015 4:04:04 AM Anu said:
can u please help me to create code for "when I attach a file that stores in a folder sometimes if we attach a file may be some problems it will not store in the folder.i want to check the folder and if file is not attached I want a alert message otherwise continue the process
On Tuesday, November 03, 2015 9:29:29 AM Anu said:
Hi Imar

I am waiting for your answer please help me
can u please help me to create code for "when I attach a file that stores in a folder, sometimes if we attach the file will not store in the folder due to some problems. i want to check the folder and if file is not attached I want a alert message otherwise continue the process"
On Tuesday, November 03, 2015 7:02:19 PM Imar Spaanjaars said:
Hi there,

You can use try/catch in C# / VB and then inside the catch block (which runs when an exception occurs) check if the file exists and then deal with that in some way.

Imar

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.