Sunday, 11 January 2015

How to send a simple email using ASP.NET 2.0 and C#


Sending an E-Mail Using ASP.Net

This tutorial will show you how to send a simple email message using ASP.NET 2.0 and C#

Introduction

Sending email is a very common task in any web application for many purposes.

Sending e-mails with ASP.NET is pretty straight forward. The .NET framework comes with an entire namespace for handling e-mails, the System.Net.Mail namespace. In the following examples, we will use two classes from this namespace: The MailMessage class, for the actual e-mail, and the SmtpClient class, for sending the e-mail. As you may be aware, mails are sent through an SMTP server, and to send mails with the .NET framework, you will need access to an SMTP server. If you're testing things locally, the company that supplies your with Internet access, will usually have an SMTP server that you can use, and if you wish to use one of these examples on your actual website, the company that hosts your website will usually have an SMTP server that you can use. Go through the support pages to find the actual address - it's usually something along the lines of smtp.your-isp.com or mail.your-isp.com.


First, you will need to import the System.Net.Mail namespace.

protected void MailSendBtn_Click(object sender, EventArgs e)
{

try

{
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("your.own@mail-address.com");
mailMessage.From = new MailAddress("another@mail-address.com");
mailMessage.Subject = "ASP.NET e-mail test";
mailMessage.Body = "Hello world,\n\nThis is an ASP.NET test e-mail!";
SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com");
smtpClient.Send(mailMessage);
Response.Write("E-mail sent!");
}
catch(Exception ex)
{
Response.Write("Could not send the e-mail - error: " + ex.Message);
}
}

No comments:

Post a Comment

Working with 3- Tier Architecture in C#

  Introduction In this article we will learn Use to 3- Tier architecture in C#.NET application. 3-Tier architecture is very famous and ...