HostOnNet Blog

Sending Authenticated mails from ASP.NET

Looking for Linux Server Admin or WordPress Expert? We can help.

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

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

        message.From = fromEmail;
        message.To.Add("[email protected]"); 

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

        smtpClient.Send(message);
    }
}

Posted in ASP.NET, Windows

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.