HostOnNet Blog

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" %>
<head runat="server"><title>Email Test Page</title></head>
    <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>

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("", "password"); 
        MailMessage message = new MailMessage(); 
        MailAddress fromEmail = new MailAddress(""); 

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

        message.From = fromEmail;

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


Posted in ASP.NET, Windows