Friday, July 23, 2010

Sending Email using ASP.NET 4

Sending and email would be an integral part of any web application and with .NET framework its very simple - you just need few lines of codes! Now here we go into the details:

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:

  1. MailMessage - represents an email message; has properties like From, To, Subject, Body, and so on
  2. 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:
  1. Create a MailMessage object
  2. Assign its properties
  3. Create an instance of the SmtpClient class
  4. 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)
  5. Send the MailMessage via the SmtpClient object's Send method
Below is a sample page to send an email with its aspx and code behind pages included.



The aspx page:
 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.Web.UI.WebControls;
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