Monday, June 11, 2007

Sending Email Using - ASP.NET C#

To send a mail in ASP.NET 2.0 we need to import the namespace System.Mail.Net.
This namespace contains classes to send electronic mail to a Simple Mail Transfer Protocol(SMTP) server for delivery.There are many classes in this namespace, but the two main classes used to send a mails are SmtpClient and MailMessage.
The SMTPClient Class transmits email to the SMTP host that you designate for mail delivery.
MailMessage Class is used to create a mail Mesasage.
We will discuss other classes in detail in afterwards,

SMTPClient and MailMessage Classes

Let us take a look on a simple application used to send a mail,
You can use the same logic to send mails from command line application, windows application or a web application.
In the program given below I am writing a windows application to send mail.

This is just the cs file of the application :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail; // This name needs to be imported
namespace Email
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{

}
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage(txtFrom.Text, txto.Text, txtSubject.Text, txtBody.Text);
SmtpClient emailClient = new SmtpClient(txtSMTP.Text);
emailClient.Send(mail);
label6.Text = "Message Sent Successfully";
}
catch (Exception exp)
{
label6.Visible = true;
label6.Text = exp.ToString();
}
}
}
}


Note : I am thankful to msdn and www.aspnettutorials.com

No comments: