Sending E-Mail in ASP.NET and C#

ASP.NET Comments Off on Sending E-Mail in ASP.NET and C#

Sending e-mail in is a simple two step process. First you have to add the mail settings in the web.config file. Adding this will enable your site to send mail. Next, Create a aspx page to send mail using this settings. This code can be used in any other pages to send mail.


1. Open the web.config file of your website.
2. Add the following code inside the configuration element(<configuration>). To remember just above the </configuration> tag.

 <smtp deliveryMethod="Network" from="MyName &lt;;">
 <network host="" userName="" password="Password"/>



1. create an aspx page with C# as the programming language.
2. Open the code behind file and add the System.Net.Mail Namespace on top as show below.

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;


3. Adding this namespace enables to use the mail class to send mails.
4. Add the following code in the page load section. You can add this in any other event.

protected void Page_Load(object sender, EventArgs e)
 MailMessage myMailMessage = new MailMessage();

 myMailMessage.Subject = "My New Mail";
 myMailMessage.Body = "This is my test mail to check";
 myMailMessage.From = new MailAddress("", "MyName");
 myMailMessage.To.Add(new MailAddress("", "receiver name"));

 SmtpClient mySmtpClient = new SmtpClient();




Imports System.Net.Mail

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

 Dim myMailMessage As New MailMessage()

 myMailMessage.Subject = "My New Mail"
 myMailMessage.Body = "This is my test mail to check"
 myMailMessage.From = New MailAddress("", "MyName")
 myMailMessage.[To].Add(New MailAddress("", "receiver name"))

 Dim mySmtpClient As New SmtpClient()

 End Sub

5. The above code creates a mailmessage object. Adds the subject, from address, from name, receiver’s address, receiver’s name to the mail message object.
6. Then creates smtpclient object to send message.
7. The mail is sent by calling the send method with maimessage object.

Points to remember

1. the username provided in the web.config file and the from address in the myMailMessage object should be same because most of the hosting providers requires authentication to send mail. So the authentication email and from address should be same.

2. If you try to send mail from your local ISP you can change the network port number to 2525(in web.config file) in case if your local ISP blocks the port 25(port 25 is the default SMTP PORT).
<network host=”” userName=”” password=”Password” port=”2525″/>



Back to Top