Sending email from ASP.Net 4 - C# sample code
Below is sample code showing how to send email from ASP.Net 4 (currently in beta as of this posting) using C#. With this code I am assuming that the server already has a local SMTP service installed, so I use "localhost" to relay the email.
Here is the SendMail.aspx page:
<% @ Page Language ="C#" AutoEventWireup ="true" CodeFile ="SendMail.aspx.cs" Inherits ="SendMail" %>
<! 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 >
Here is the source code of the SendMail.aspx.cs page:
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();
}
}
}
Please enable JavaScript to view the comments powered by Disqus.
blog comments powered by