Sending Authenticated mails from ASP.NET

The following code uses System.Net.Mail to send emails from ASP.NET applications with authentication.

Front End Code (SendMail.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendMail.aspx.cs" Inherits="SendMail" %>
<html>
<head runat="server"><title>Email Test Page</title></head>
<body>
    <form id="form1" runat="server">
        Subject: <asp:TextBox ID="txtSubject" runat="server" /><br>
        Message Body:<br>
        <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine" Width="270px" /><br>
        <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" /><br>
    </form>
</body>
</html>

Back End Code (SendMail.aspx.cs)

using System;
using System.Net;
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)
    {
        SmtpClient smtpClient = new SmtpClient();
        NetworkCredential cred = new NetworkCredential("email@domain.com", "password"); 
        MailMessage message = new MailMessage(); 
        MailAddress fromEmail = new MailAddress("from@anydomain.com"); 

        smtpClient.Host = "servername or ip address";
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = cred;

        message.From = fromEmail;
        message.To.Add("to@anydomain.com"); 

        message.Subject = txtSubject.Text;
        message.Body = txtBody.Text;

        smtpClient.Send(message);
    }
}

Posted in ASP.NET, Windows