Microsoft & .NETASPUsing ASP.NET to Send E-Mail-Including Attachments

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.

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:

Listing 1

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:

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:

Listing 3

mail.Attachments.Add(new MailAttachment(strdir+strfilename));

Finally, you have to delete the uploaded file, as shown in Listing 4:

Listing 4

File.Delete(strdir+strfilename);

The project also makes use of Exception Handling and ASP.NET validation controls to avoid errors. For a change, I have also used a little JavaScript to handle the error of the File control. The ASP.NET part of the code is given in Listing 5:

Listing 5

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Mail" %>
<%@ Import Namespace="System.IO" %>

<script language = "javascript">
  function Tocheck(frmemail)  {
    if(frmemail.txtFile.value  == "")  {
      alert("Please attach a file");
      frmemail.txtFile.focus();
      return(false);
    }
  }
</script>

<script runat="server">

void btnSubmit_Click(Object sender, EventArgs e) {

  MailMessage mail = new MailMessage();
  mail.From        = txtFrom.Text;
  mail.To          = txtTo.Text;
  mail.Subject     = txtSubject.Text;
  mail.Body        = txtMsg.Text;
  mail.BodyFormat  = MailFormat.Html;

  'Change the path appropriately
  string strdir = "D:temp";
  string strfilename = 
      Path.GetFileName(txtFile.PostedFile.FileName);
  txtFile.PostedFile.SaveAs(strdir+strfilename);
  mail.Attachments.Add(new MailAttachment(strdir+strfilename));

  try
  {
    SmtpMail.Send(mail); 
  }
  catch(Exception ex)
  {
    Response.Write("Exception Occured:   " +ex);
  }
  finally
  {
    Response.Write("Your E-mail has been sent sucessfully");
  }
  // Uploaded file deleted after sending e-mail
  File.Delete(strdir+strfilename);
}

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 ananddotnet@yahoo.co.in.

# # #

Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.

Latest Posts

Related Stories