Send Email using ASP.NET 2.0
Introduction
A common thing you do with Web Development is to send emails, I will show you here how to send emails using ASP.Net v 2.0, and also using the authentication for a SMTP server.
The namespace for sending mail within ASP.Net v 2.0 is not System.Web.Mail anymore this is replaced by System.Net.Mail
This article explains how to use System.Net.Mail namespace to send emails.
Technical Details:
The Send mail functionality is similar to Dotnet 1.1 except for few changes.
1. System.Net.Mail.SmtpClient is used instead of System.Web.Mail.SmtpMail (obsolete in Dotnet 2.0).
2. System.Net.MailMessage Class is used instead of System.Web.Mail.MailMessage (obsolete in Dotnet 2.0)
3. The System.Net.MailMessage class collects From address as MailAddress object.
4. The System.Net.MailMessage class collects To, CC, Bcc addresses as MailAddressCollection.
5. MailMessage Body Format is replaced by IsBodyHtml
Code Sample:
using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
#region "Send email"
protected void btnSendmail_Click(object sender, EventArgs e)
{
// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
// System.Net.Mail.SmtpClient is the alternate class for this in 2.0
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost
smtpClient.Host = "localhost";
//Default port will be 25
smtpClient.Port = 25;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add("admin1@yoursite.com");
message.Subject = "Feedback";
// CC and BCC optional
// MailAddressCollection class is used to send the email to various users
// You can specify Address as new MailAddress(admin1@yourdomain.com)
message.CC.Add("admin1@yourdomain.com");
message.CC.Add("admin2@yourdomain.com");
// You can specify Address directly as string
message.Bcc.Add(new MailAddress("admin3@yourdomain.com"));
message.Bcc.Add(new MailAddress("admin4@yourdomain.com"));
//Body can be Html or text format
//Specify true if it is html message
message.IsBodyHtml = false;
// Message body content
message.Body = txtMessage.Text;
// Send SMTP mail
smtpClient.Send(message);
lblStatus.Text = "Email successfully sent.";
}
catch (Exception ex)
{
lblStatus.Text = "Send Email Failed.
" + ex.Message;
}
}
#endregion
}

No comments:
Post a Comment