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

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
           
width: 169px;
        }
   
</style>
</
head>
<
body>
    <form id="form1" runat="server">
        <div>
            <table border="0" cellpadding="0" cellspacing="0" style="width: 464px">
                <tr>
                    <td class="auto-style1">To:
                   
</td>
                    <td>
                        <asp:TextBox ID="txtTo" runat="server" Width="204px"></asp:TextBox>
                    </td>
                </tr>
 
               
<tr>
                    <td class="auto-style1">Subject:
                    
</td>
                    <td>
                        <asp:TextBox ID="txtSubject" runat="server" Width="201px"></asp:TextBox>
                    </td>
                </tr>
 
               
<tr>
                    <td class="auto-style1">Attachment:
                   
</td>
                    <td>
                        <asp:FileUpload ID="fileUploader" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td valign="top" class="auto-style1">Body:
                   
</td>
                    <td>
                        <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Height="150" Width="200"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1">&nbsp;
                    </td>
                </tr>
 
               
<tr>
                    <td class="auto-style1"></td>
                    <td>
                        <asp:Button ID="bttn_Send" Text="Send Mail" runat="server" OnClick="bttn_Send_Click" />
                    </td>
                </tr>
            </table>

 
       
</div>
    </form>
</
body>
</
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

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {

    }
    
/// <summary>
    /// For Sending Email with attachment, with Gmail.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void bttn_Send_Click(object sender, EventArgs e)
    {
        
string from = "Your Gmail Username"//example:- [email protected]
        using (MailMessage mail = new MailMessage(from, txtTo.Text))
        {
            mail.Subject = txtSubject.Text;
            mail.Body = txtMessage.Text;
            
if (fileUploader.HasFile)
            {
                
string fileName = Path.GetFileName(fileUploader.PostedFile.FileName);
                mail.Attachments.Add(
new Attachment(fileUploader.PostedFile.InputStream, fileName));
            }
            mail.IsBodyHtml = 
false;
            
SmtpClient smtp = new SmtpClient();
            smtp.Host = 
"smtp.gmail.com";
            smtp.EnableSsl = 
true;
            
NetworkCredential networkCredential = new NetworkCredential(from, "your gmail password");
            smtp.UseDefaultCredentials = 
true;
            smtp.Credentials = networkCredential;
            smtp.Port = 587;
            smtp.Send(mail);
            ClientScript.RegisterStartupScript(GetType(), 
"alert""alert('Message has been sent successfully.');"true);
        }
    }
}

  
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:

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:

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


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

 

 smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
NetworkCredential networkCredential = new NetworkCredential(from, "your gmail password");

smtp.UseDefaultCredentials = true;

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.

smtp.Credentials = new System.Net.NetworkCredential("username", "password");

Smtp.Credentials specifies the Network Crendentials 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.

smtp.EnableSsl = true;

Smtp.Send sends the mail so please add your MailMesssage object here, based on properties, your mail will be sent. 

 

Up Next
    Ebook Download
    View all
    Learn
    View all