Sending Email In ASP.NET 2.0

Posted by: Suprotim Agarwal , on 7/26/2007, in Category ASP.NET
Views: 235121
Abstract: Sending email's from web applications is a very common requirement in most projects. This article explores how to send Emails in ASP.NET 2.0 with attachments.
Sending Email In ASP.NET 2.0
In ASP.NET, sending emails has become simpler. The classes required to send an email are contained in the System.Net.Mail. The steps required to send an email from ASP.NET are as follows :
Step 1: Declare the System.Net.Mail namespace
C# - using System.Net & System.Net.Mail;
VB.NET - Imports System.NET & System.Net.Mail
Step 2: Create a MailMessage object. This class contains the actual message you want to send. There are four overloaded constructors provided in this class. We will be using
C# - public MailMessage ( string from, string to, string subject, string body )
VB.NET - public MailMessage (String From, String to, String subject, String body)
The constructor of this MailMessage class is used to specify the sender email, receiver email, subject, body.
MailMessage message = new MailMessage            ("","","Testing","This is a test mail");
Dim message As MailMessage = New MailMessage ("","","Testing","This is a test mail")
Step 3: To add an attachment to the message, use the Attachment class.
string fileAttach = Server.MapPath("myEmails") + "\\Mypic.jpg";
Attachment attach = new Attachment(fileAttach);
Dim fileAttach As String = Server.MapPath("myEmails") & "\Mypic.jpg"

Dim attach As Attachment = New Attachment(fileAttach) message.Attachments.Add(attach)

Step 4:After creating a message, use the SmtpClient to send the email to the specified SMTP server. I will be using ‘localhost’ as the SMTP server.

SmtpClient client = new SmtpClient("localhost");
Additionally, if required, you
client.Timeout = 500;
// Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Dim client As SmtpClient = New SmtpClient("localhost")


Additionally, if required, you client.Timeout = 500

' Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client's behalf.

client.Credentials = CredentialCache.DefaultNetworkCredentials 

That’s it. It’s that simple.
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.
      <smtp from="">
        <network host="somesmtpserver" port="25" userName="name" password="pass" defaultCredentials="true" />
References :
In this short article, we explored how easy it is to send Email’s with attachments using the classes in System.Net.Mail. This approach of sending mails will remain the same for web as well as windows application.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by pranav yesane on Tuesday, November 13, 2007 2:25 AM
i am happy with steps that you mentioned i will be more happy if you declar code with VB .net also
Comment posted by Suprotim Agarwal on Thursday, November 15, 2007 8:25 AM
Dear pranav,
The code is now in
Comment posted by Nickolaos on Friday, November 16, 2007 11:46 AM
   Very useful article.
I need some additional explanations about Step 1 :
- I don't know how to declare namespase
- I don't know where in the application that Step1 takes place
I'm not a programmer I can only read and modify a code .
Can you point me  out the right place to add or modify the code.
   Step 4 says :
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.
        <networkhost="somesmtpserver"port="25"userName="name"password="pass"defaultCredentials="true" />

   My hosting company wants me to use port 8025 instead of port 25 therefore that particular part from my web.config looks like that:

**** Edited by admin ****
Please do not provide username and passwords to avoid being
Comment posted by Suprotim Agarwal on Saturday, November 17, 2007 12:43 AM
Every program that you write in .NET comes with a default namespace. Do for eg: if you have created a file called Default.aspx with code behind, check the Default.aspx.cs or .vb. You will find in the top most sections some using(C#) or Import( statements that declare namespace.

You can use the port number the hosting company suggests you to use. I do not see much of a problem in that.

Later in the day, I will try and create an example for you and post the code file over here.

Comment posted by hi on Wednesday, January 9, 2008 5:35 AM
Comment posted by fsdf on Thursday, March 20, 2008 7:53 AM
Comment posted by aaaa on Thursday, March 20, 2008 7:53 AM
Comment posted by km' on Thursday, March 27, 2008 7:33 PM
Comment posted by serfer on Tuesday, April 1, 2008 2:29 PM
It's very useful code. I just have one question. In my case, I'm using Exchange Server, and I have McAfee Antivirus, so I had to give permission to my application in the Wormstopper options.  Is it the right thing to do?  Isn't it dangerous?  What are the risks?  ...Does anyone can make a malicious program named as mine to get into my server?  Thanks.
Comment posted by lok on Thursday, April 10, 2008 1:59 AM
fghfgh fghfgh f hfgh
Comment posted by Baji on Monday, April 21, 2008 3:38 AM
while iam sending mail from page.. it dont send what happend i dont get it..and i also make the proper setting in IIS also...still Mails r not sending out..why?
Comment posted by premsankar on Monday, June 30, 2008 5:42 AM
that code  doesnt work for me....
in 2 nd steo when i declare
  Dim message As MailMessage = New MailMessage("", "", "Testing", "This is a test mail")
Comment posted by kirti on Wednesday, July 23, 2008 6:04 AM
I want to develop an email application with multipule attchements of listbox in 2.0
plz help
Comment posted by puspanjali jena on Thursday, September 11, 2008 3:32 AM
i want detail explanation to send mail.I couldn't implement this amount of codes to develop my project.
plz help
Comment posted by NITESH SAXENA on Friday, December 19, 2008 2:52 AM
nice article but how can we know the smtp server name
Comment posted by sdfads on Wednesday, February 11, 2009 6:44 AM
Comment posted by kkkk on Tuesday, March 10, 2009 3:01 AM
Im use
MailMessage message = new MailMessage ("from id here","to id here","Testing","This is a test mail");

        SmtpClient client = new SmtpClient("localhost");
but i got an error
"No connection could be made because the target machine actively refused it "
Comment posted by Suprotim Agarwal on Tuesday, March 10, 2009 8:22 AM
kkkk: There could be a possibility of firewall blocking your connection.
Comment posted by Alexander Perez on Thursday, April 16, 2009 2:41 PM
I tried the code give no errors but i don't get the message. Im using my desktop to work with the aplication but at smtp i'm giving the exhange smtp but it dosn't do anything. Any security issues tha i'm missing? Please help.
Comment posted by Suprotim Agarwal on Friday, April 17, 2009 5:57 AM
Can you post some code over here. Make sure you remove the actual SMTP details and username/pwds while posting the code, as it is not advisable to post security details on an open site.
Comment posted by Arti on Thursday, May 14, 2009 3:25 AM
in web.config file i wrote
    <add key="MyMailServer" value ="localhost"/>
    <add key="MyMailServerPort" value ="25"/>
n in asp.vb page i wrote this

Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click

        'send message

        Dim strMsg As String
        strMsg = txtMessage.Text

        mTo = Trim(txtTo.Text)
        mFrom = Trim(txtFrom.Text)
        mSubject = Trim(txtSubject.Text)
        mMsg = Trim(txtMessage.Text)

        mMailServer = ConfigurationManager.AppSettings.Get("MyMailServer")
        mPort = ConfigurationManager.AppSettings.Get("MyMailServerPort")
        mCC = Trim(txtCC.Text)


            Dim message As New MailMessage(mFrom, mTo, mSubject, mMsg)

            If fileAttachments.HasFile Then
                Dim attached As New Attachment(Trim(fileAttachments.PostedFile.FileName.ToString()))
            End If

            If mCC <> "" Or mCC <> String.Empty Then
                Dim strCC() As String = Split(mCC, ";")
                Dim strThisCC As String
                For Each strThisCC In strCC
            End If

            Dim mySmtpClient As New SmtpClient(mMailServer, mPort)
            mySmtpClient.UseDefaultCredentials = True
            mySmtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis

            MessageBox("The mail message has been sent to " & message.To.ToString())

        Catch ex As FormatException

            MessageBox("Format Exception: " & ex.Message)

        Catch ex As SmtpException

            MessageBox("SMTP Exception:  " & ex.Message)

        Catch ex As Exception

            MessageBox("General Exception:  " & ex.Message)

        End Try
end Sub

  i mgetting the mail sent message But not Getting any mail
in my mailbox
will u All Experts Give me the reason Plzzzzzz
Comment posted by bingo play live on Monday, June 1, 2009 1:00 AM
these steps are really very usefull for me m a software engg.but plz discribe these steps in more detail with example.
Comment posted by binay on Wednesday, June 17, 2009 5:10 AM
Comment posted by sanjay on Monday, June 29, 2009 5:09 AM
I successfuly send mail by gmail but when i send from my company relay server then i failure. my code foolwing way please any one help me.
Web Conf.->
         <smtp deliveryMethod="Network">
            <network host="" port="25" defaultCredentials="true" userName="" password=""></network>
   </> file ->
  MailMessage m = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            //  smtp.Host = "";
            //smtp.Port = 25;

          // Default port will be 25
            smtp.Host = "";
             //smtp.Port = 587;
            smtp.Port = 25;
            smtp.EnableSsl = true;

            m.From = new System.Net.Mail.MailAddress(txtFrom.Text, "");
            m.Priority = MailPriority.High;
            m.Subject = txtSubject.Text;
            m.Body = txtMessage.Text;
            m.IsBodyHtml = false;
            // CC and BCC optional
            // MailAddressCollection class is used to send the email to various users
            // You can specify Address as new MailAddress("")
            // You can specify Address directly as string
Comment posted by Suprotim Agarwal on Thursday, July 2, 2009 2:15 AM
Sanjay: Check out with your admin if the server requires credentials to send the mail!
Comment posted by Arunkumar on Friday, July 3, 2009 3:26 AM
Dim MAtt As Net.Mail.Attachment
            Dim emailClient As New SmtpClient("localhost server")
            Dim message As New MailMessage
            Dim FromAdd As New MailAddress("ur local host mail id(")

            Dim ToAdd As New MailAddress("")

            message.From = FromAdd
            message.Subject = "Request For Quotation E-MAIL On " & Today
            MAtt = New Net.Mail.Attachment(" file path")

            emailClient.UseDefaultCredentials = False
            'mension from address and ur password here
            emailClient.Credentials = New Net.NetworkCredential("local host mail id ", "paswd")
            ' Dim userinfo As New CreateUserWizard(
            emailClient.Host = "local host server"
            emailClient.Port = 25

            MsgBox("Mail has sent")
Comment posted by sanjay on Monday, August 10, 2009 8:21 AM
please help me,
  i want to send email by defualt credential but i failure to send and also explai i must to send mail server userName and password if i want to send email using defualt credentia; please reply me for my job.
Comment posted by Suprotim Agarwal on Tuesday, August 11, 2009 1:17 AM
Sanjay: You provide very little information, not enough to help you out.

What error do you get when you send the email? Is it 401? Ask your admin to check the server for events, specifially the 'Security' event log and see if there are any Failure Audits occuring.

This video should also help you out
Comment posted by sunny on Wednesday, August 12, 2009 6:13 AM
iam getting the error while deleting the file in the localdrive which sent as an attachment. the error the process access the file"C:\abc.xml" because it is used by another process. after sending the mail iam disposing the mail message object also. like mailmessage.dispose().can anybody help me.
Comment posted by Pawan Sugandhi on Monday, October 5, 2009 3:02 AM
Comment posted by zenich on Monday, October 12, 2009 3:40 PM
I am trying to send mail with's perfectly working fine but when i hosted to different web server..i am getting an error saying that "Can not find part of the path " Please advise if anybody knows about the error..Thankx in Advance
Comment posted by dhixa on Wednesday, December 16, 2009 2:22 AM
plz send me detailed code about sending a mail to a particular person whn i press a submit button in my .aspx file
Comment posted by ashwin marthak on Thursday, February 11, 2010 2:24 PM
thanks it is very useful for us....
Comment posted by patel sandip on Monday, March 29, 2010 9:28 AM
i am create the sending mail via project connected the
Comment posted by saranya elangovan on Thursday, June 10, 2010 2:46 AM
how to create a sending mail in with c# sharp coding with run on IIS SERVER without publishing any domain name or Host Server
Comment posted by saranya on Thursday, June 10, 2010 2:54 AM
while iam sending mail from page.. it dont send what happend i dont get it..and i also make the proper setting in IIS also...still Mails r not sending out..why? if (TextBox12.Text != "" && TextBox13.Text  != "" && TextBox14.Text != "")
            MailMessage mail = new MailMessage();


            mail.From = new MailAddress("");

            mail.Subject = "Comments from Visitors";

            string Body = TextBox12.Text;

            mail.Body = Body;

            mail.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient();

            smtp.Host = ""; //Or Your SMTP Server Address

            smtp.Credentials = new System.Net.NetworkCredential("", "123456");//Or your Smtp Email ID and Password

            smtp.EnableSsl = true;

          // smtp.Send(mail);
            Label15.Text = "Your Mail Send Successfully !";

            Label16.Text = TextBox12.Text;

          //Label.Text = txtemailid.Text;

            TextBox12.Text = "";

            TextBox13.Text = "";

            TextBox14.Text = "";

            //llbemailid.Visible = true;

            //llbuser.Visible = true;
but it not send to the prompt msg to the fetching address y? wats the reason? but i'm not hosted any websit but i want to send the mailing to the admin please give the correct coding to me
Comment posted by anand on Monday, July 5, 2010 3:12 AM
Hey saranya u just have mention the port number for gmail...... 587
Comment posted by yuanchao on Thursday, July 8, 2010 2:39 AM
Comment posted by hari on Friday, August 27, 2010 2:07 AM
hai i want sending mail from using yahoo portnumber and host name only
Comment posted by Ady on Thursday, November 11, 2010 6:26 AM
I am using dotnet 1.1. I need to send mail with attachments to a configured email-id of an organization. There could any number of attachments. So i wanted to know, is there any limitations on the number of attachments or the limitation on size of attachments.
Comment posted by Ady on Thursday, November 11, 2010 6:27 AM
I am using dotnet 1.1. I need to send mail with attachments to a configured email-id of an organization. There could any number of attachments. So i wanted to know, is there any limitations on the number of attachments or the limitation on size of attachments.
Comment posted by Aftab on Tuesday, December 14, 2010 12:33 AM
hi all, i used this code to send mail from an page.
MailMessage message = new MailMessage            ("","","Testing","This is a test mail");

But it doesnt work . Any solutions ?
Comment posted by rajkumar on Thursday, December 23, 2010 12:13 AM
i want code for automatic sending response to user by emailing or sms after clicking sub mitt's urgent
Comment posted by nnn on Saturday, December 25, 2010 2:42 AM
Comment posted by gg on Saturday, March 5, 2011 1:06 AM
Comment posted by michael on Wednesday, March 9, 2011 3:27 AM
Use MailMessage and SmtpClient class to build the sending mail program.
I already answered in other website. See the below link :
Comment posted by Alok kumar on Friday, April 8, 2011 6:59 AM
would u please tell me how to download file without Asking SaveAs Option ,
I want Save file Automaticaly to Root Folder of My Server When I Click On Download Button
Comment posted by chetan on Saturday, September 17, 2011 1:22 PM
hey we are using .net 3.5 and sql server2005 v r nt able send mail on submit button error like sending fail port 25 and host name is over own which v buy wht to do
Comment posted by pankaj on Monday, November 7, 2011 6:27 AM
iam using .net 4.0 and this code is not work properly........ like mail message shown warning...........
Comment posted by dsf on Tuesday, November 22, 2011 4:14 AM
Comment posted by john on Wednesday, January 11, 2012 2:41 AM
Comment posted by john on Wednesday, January 11, 2012 2:43 AM
Comment posted by crazy_girl on Wednesday, January 11, 2012 2:44 AM
hi john..are u single?
Comment posted by keshav_roy on Thursday, March 8, 2012 10:44 PM
i did the same but i m having an exception as:
The remote name could not be resolved: ''
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote name could not be resolved: ''

Plz solve this problem...

Comment posted by Ravinder Kumar on Monday, April 2, 2012 1:20 AM
Please help me,In this error will be solve.
[SmtpException: SSL must not be enabled for pickup-directory delivery methods.]
   System.Net.Mail.SmtpClient.Send(MailMessage message) +1757
   _Default.SendEmail_Click(Object sender, EventArgs e) in b:\WebSite1\send mail\Default.aspx.cs:47
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Comment posted by VIVEK KUMAR on Tuesday, April 10, 2012 10:56 AM
Simply use this code for sending email in

using System;

using System.Data;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Text;

using System.Net;

using System.Net.Mail;

/// <summary>

/// Summary description for contact_us

/// </summary>

public partial class contact_us:Page


    void page_Load(object sender, EventArgs e)


        this.MaintainScrollPositionOnPostBack = true;


    protected void cmdSubmit_Click(object sender, EventArgs e)


        MailMessage mailMessage = new MailMessage();


        mailMessage.Subject = "Support Team";

        //mailMessage.Body = "<html><body>This is a test</body></html>";

        StringBuilder sb = new StringBuilder();



        sb.Append("<br><strong>Name :</strong>" + Request.Form["Name"].ToString());

        sb.Append("<br><strong>Email :</strong>" + Request.Form["email"].ToString());

        sb.Append("<br><strong>phone :</strong>" + Request.Form["phone"].ToString());

        sb.Append("<br><strong>Business :</strong>" + Request.Form["business"].ToString());


mailMessage.Body = sb.ToString();


        mailMessage.IsBodyHtml = true;

        // Create the credentials to login to the gmail account associated with my custom domain

        string sendEmailsFrom = "";


        string sendEmailsFromPassword = "Your Password";


        mailMessage.From = new MailAddress("");

        NetworkCredential cred = new NetworkCredential(sendEmailsFrom, sendEmailsFromPassword);

        SmtpClient mailClient = new SmtpClient("", 587); // set your smtp server and smtp port

        mailClient.EnableSsl = true;

        mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

        mailClient.UseDefaultCredentials = false;

        mailClient.Timeout = 20000; // Set timeout

        mailClient.Credentials = cred;




Reference :!/2012/04/sending-email-in-aspnet-using-smtp.html
Comment posted by Vibs on Friday, June 8, 2012 1:24 AM
Thanks a lot. It helped me .. however you forgot to add that to use "CredentialCache.DefaultNetworkCredentials" you need to import System.Net Namespace too. Please edit that and do the needful.
Comment posted by Admin on Friday, June 8, 2012 4:35 AM
Thanks Vibs! Fixed!
Comment posted by nikhil on Sunday, June 10, 2012 5:40 PM
its working.. but its sending the email address specified in network credentials at the place of the desired email address from where i want to send mail.
Comment posted by Rohit Kabadi on Monday, June 18, 2012 2:26 AM

I am facing one problem after sending mail with attachment.I want to delete the attachment but it give error that the file is used by another process.

Any help from your side is appreciated.


Comment posted by Eshant Kapoor on Tuesday, July 31, 2012 12:33 AM
i am facing problem in sending mail on contact form
pls help me any one
my code on button is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

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

    protected void Button1_Click(object sender, EventArgs e)
        nsaerows.clsqueryprp objprp = new nsaerows.clsqueryprp();
        nsaerows.clsquery obj = new nsaerows.clsquery();
        objprp.p_qryname = txtname.Text;
        objprp.p_qryemail = txtemail.Text;
        objprp.p_qrymsg = txtqrymsg.Text;
        objprp.p_qrydate = DateTime.Now;

       MailMessage mm = new MailMessage("",txtemail.Text, "Thanks for Submitting your Query.", "You are important to us. We will revert back to you as soon as possible.");
        SmtpClient c = new SmtpClient(",587");
        txtname.Text = "";
        txtemail.Text = "";
        txtqrymsg.Text = "";


Comment posted by we on Monday, September 10, 2012 7:52 AM
Comment posted by jhghjgvhj on Wednesday, January 16, 2013 1:41 AM
Comment posted by try on Monday, March 25, 2013 5:31 AM
Comment posted by sd on Sunday, March 31, 2013 12:35 PM
Comment posted by 878 on Monday, December 16, 2013 3:52 AM
Comment posted by Kiran on Wednesday, August 27, 2014 6:43 AM  Superb stuff and article.I just loved reading it. Keep writing.
Comment posted by bgasri on Monday, April 20, 2015 2:44 PM
How to Resolve a SMTP Server Secure Connection and Authentication 5.5.1 Required Error | The SMTP Server Requires a Secure Connection or the Client was not authenticated