Using ASP.NET to Send E-Mail-Including Attachments
Sending an e-mail with attachments is very easy with the .NET Framework. You don't have to learn complicated syntaxes and other commands to achieve the task. In this article, you will learn how to send e-mails with an attachment using ASP.NET. This article follows up on my previous article, Using ASP.NET To Send Email.
Before getting started, you should create a user interface using WebForm controls, as shown in Figure 1.
An ideal way to attach a file along with an e-mail is to upload the file to a temporary location on your server and then send it along with an e-mail. After the e-mail has been sent, the uploaded file can be deleted with the help of the Delete() method of the File class under the System.IO namespace. The code snippet given in Listing 1 enables you to upload a file to a folder named temp on your server:
1 string strdir = "D:\\temp\\"; 2 string strfilename = Path.GetFileName( txtFile.PostedFile. FileName); 3 txtFile.PostedFile.SaveAs(strdir+strfilename);
Note: The line numbers are given for the sake of explanation and do not form part of the source code.
Make sure to create the specified folder and change the path (Line 1) before attempting to execute the program. In the above code, I have used the HTML File control so that users can browse for the required file (See Figure 1). As you may know, an HTML control can be converted into an ASP.NET server control with the addition of the runat = "server" attribute. The system retrieves and saves the file using the PostedFile property. Because the HTML file control is used, you have to specifically give the enctype attribute of the Form tag, as shown in Listing 2:
<form method = "post" name = "frmemail" runat = "server" enctype = "multipart/form-data" onSubmit = "return Tocheck(this)">
Hot Tip: Visual Studio "Whidbey" ships with a built-in control named "FileUpload". Hence, the usage of the HTML File control can be avoided. Also, there is no need to give the enctype attribute as shown above. The new control automatically handles the encryption.
After the file has been uploaded, you can attach it to your e-mail message as shown in Listing 3:
Finally, you have to delete the uploaded file, as shown in Listing 4:
The complete code for the above project can be downloaded by clicking here.
About the Author
Anand Narayanaswamy, a Microsoft Most Valuable Professional, works as an independent consultant and technical writer. Anand runs learnXpress.com and specializes in C#, ASP.NET, Visual Basic .NET, ASP, Visual Basic 6.0, and in the development of courseware, technical articles, documentation, and reviews of products and books. You can post your queries regarding this article at www.learnxpress.com/forums. Reach him at firstname.lastname@example.org.
# # #