For sending emails we will look into classes provided in the System.Net.Mail namespace. Previously in .NET 1.x these functionalities were in System.Web.Mail namespace which has now been deprecated. There are a bunch of classes defined in this namespace but the ones that we should be concerned about are:
- MailMessage - represents an email message; has properties like From, To, Subject, Body, and so on
- SmtpClient - sends a specified MailMessage instance to a specified SMTP server.
Having know the basics you can follow the following steps to complete the task at hand:
- Create a MailMessage object
- Assign its properties
- Create an instance of the SmtpClient class
- Specify details about the SMTP server to use (if they're not already specified within Web.config - Yes! you can provide the details of SMTP server in Web.config file but the details of it are out of scope for our task at hand - just the basics here)
- Send the MailMessage via the SmtpClient object's Send method
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<div>
Message to:
<asp:TextBox ID="txtTo" runat="server">asp:TextBox>
<br />
Message from:
<asp:TextBox ID="txtFrom" runat="server">asp:TextBox>
<br />
Subject:
<asp:TextBox ID="txtSubject" runat="server">asp:TextBox>
<br />
Message Body:
<br />
<asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine" Width="270px"><asp:TextBox>
<br />
<asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label">asp:Label>
div>
form>
body>
html>
Code behind:
using System;
using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
protected void Btn_SendMail_Click(object sender, EventArgs e)
{
MailMessage mailObj = new MailMessage(
txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
SmtpClient SMTPServer = new SmtpClient("localhost");
try
{
SMTPServer.Send(mailObj);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
}
No comments:
Post a Comment