Sending an E-Mail With Attachment Using ASP.Net

Introduction

Sending email is a very common task in any web application for many purposes. In daily development we need to add some mail functionality to our project, in this article I will show you, how you can do this.

Using the code

For sending mail from ASP.NET we use the "System.Net.Mail" namespace. Let's see how to do this.

  • Open Visual Studio
  • "File" -> "New" -> "Project..."
  • Choose "Visual C#" - "Web" then select "ASP.NET Empty Web Application"
  • Add a new aspx page

The following is the code for the design of the page.

Sendmail.aspx

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4.     <style type="text/css">  
  5.         .auto-style1 {  
  6.             width: 169px;  
  7.         }  
  8.     </style>  
  9. </head>  
  10. <body>  
  11.     <form id="form1" runat="server">  
  12.         <div>  
  13.             <table border="0" cellpadding="0" cellspacing="0" style="width: 464px">  
  14.                 <tr>  
  15.                     <td class="auto-style1">To:  
  16.                     </td>  
  17.                     <td>  
  18.                         <asp:TextBox ID="txtTo" runat="server" Width="204px"></asp:TextBox>  
  19.                     </td>  
  20.                 </tr>  
  21.    
  22.                 <tr>  
  23.                     <td class="auto-style1">Subject:  
  24.                     </td>  
  25.                     <td>  
  26.                         <asp:TextBox ID="txtSubject" runat="server" Width="201px"></asp:TextBox>  
  27.                     </td>  
  28.                 </tr>  
  29.    
  30.                 <tr>  
  31.                     <td class="auto-style1">Attachment:  
  32.                     </td>  
  33.                     <td>  
  34.                         <asp:FileUpload ID="fileUploader" runat="server" />  
  35.                     </td>  
  36.                 </tr>  
  37.                 <tr>  
  38.                     <td valign="top" class="auto-style1">Body:  
  39.                     </td>  
  40.                     <td>  
  41.                         <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Height="150" Width="200"></asp:TextBox>  
  42.                     </td>  
  43.                 </tr>  
  44.                 <tr>  
  45.                     <td class="auto-style1">   
  46.                     </td>  
  47.                 </tr>  
  48.    
  49.                 <tr>  
  50.                     <td class="auto-style1"></td>  
  51.                     <td>  
  52.                         <asp:Button ID="bttn_Send" Text="Send Mail" runat="server" OnClick="bttn_Send_Click" />  
  53.                     </td>  
  54.                 </tr>  
  55.             </table>  
  56.   
  57.    
  58.         </div>  
  59.     </form>  
  60. </body>  
  61. </html> 
In the code above we have the following 3 fields: 
  • To
  • Subject
  • Attachment
  • Message

When the user clicks the "Send" button, the mail will be sent to the specified mail address that you provide in the "txtTo" TextBox. So add the following code for the Button_Click:

SendMail.aspx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Mail;  
  7. using System.Web;  
  8. using System.Web.UI;  
  9. using System.Web.UI.WebControls;  
  10.   
  11. public partial class _Default : System.Web.UI.Page  
  12. {  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.   
  16.     }  
  17.     /// <summary>  
  18.     /// For Sending Email with attachment, with Gmail.  
  19.     /// </summary>  
  20.     /// <param name="sender"></param>  
  21.     /// <param name="e"></param>  
  22.     protected void bttn_Send_Click(object sender, EventArgs e)  
  23.     {  
  24.         string from = "Your Gmail Username"//example:- sourabh9303@gmail.com  
  25.         using (MailMessage mail = new MailMessage(from, txtTo.Text))  
  26.         {  
  27.             mail.Subject = txtSubject.Text;  
  28.             mail.Body = txtMessage.Text;  
  29.             if (fileUploader.HasFile)  
  30.             {  
  31.                 string fileName = Path.GetFileName(fileUploader.PostedFile.FileName);  
  32.                 mail.Attachments.Add(new Attachment(fileUploader.PostedFile.InputStream, fileName));  
  33.             }  
  34.             mail.IsBodyHtml = false;  
  35.             SmtpClient smtp = new SmtpClient();  
  36.             smtp.Host = "smtp.gmail.com";  
  37.             smtp.EnableSsl = true;  
  38.             NetworkCredential networkCredential = new NetworkCredential(from, "your gmail password");  
  39.             smtp.UseDefaultCredentials = true;  
  40.             smtp.Credentials = networkCredential;  
  41.             smtp.Port = 587;  
  42.             smtp.Send(mail);  
  43.             ClientScript.RegisterStartupScript(GetType(), "alert""alert('Message has been sent successfully.');"true);  
  44.         }  
  45.     }  
  46. } 
That’s it. Press F5, and run your code.

E-Mail with Attachment Using ASP.NET

Understanding the Code

In the code above, we create an object of the MailMessage class as in the following:
  1. MailMessage mail = new MailMessage();
MailMessage is the main class for sending mail, this is the part of the System.Net.Mail namespace.

The MailMessage class has properties, the important ones are: 
  • To
  • From
  • Cc
  • Bcc
  • Subject
  • Body
  • Attachments

So we add our data into specified properties as in the following:

  1. mail.Subject = txtSubject.Text;  
  2.            mail.Body = txtMessage.Text;  
  3.            if (fileUploader.HasFile)  
  4.            {  
  5.                string fileName = Path.GetFileName(fileUploader.PostedFile.FileName);  
  6.                mail.Attachments.Add(new Attachment(fileUploader.PostedFile.InputStream, fileName));  
  7.  }

For sending mail we need a SMTP Server, so in ASP.Net we have the SmtpClient class, using that class object we set its properties for the SMTP settings.

SmtpClient smtp = new SmtpClient();

The SMTPClient class has the following basic properties: 
  • Host
  • Port
  • UseDefaultCredential
  • Credentials
  • EnableSsl
  • Send

  1. smtp.Host = "smtp.gmail.com";  
  2. smtp.Port = 587;  
  3. NetworkCredential networkCredential = new NetworkCredential(from, "your gmail password");  
  4. smtp.UseDefaultCredentials = true;  
  5. smtp.EnableSsl = true;

Here in the code above smtp.Host = "smtp.gmail.com"; This is the SMTP Host address of Gmail, if you want to use any other SMTP host service then please add a different SMTP host protocol, for example for Hotmail it is smtp.live.com.

Smtp.Port=587

587 is the port for Gmail, so for any other service port you have to change the port correspondingly.

  1. smtp.Credentials = new System.Net.NetworkCredential("username""password");
Smtp.Credentials specifies the Network Credentials of your Gmail id so please add your username and password instead of ("username", "password");

The following is for a secure mail server, so you enable your SSL layer.
  1. smtp.EnableSsl = true;
Smtp.Send sends the mail so please add your MailMesssage object here, based on properties, your mail will be sent.