How to send email in ASP.NET 2.0

ASP.NET 2.0 has a built in class, System.Net.Mail, to send email. Although the legacy System.Web.Mail class is still available in ASP.NET 2.0, it is recommended that you use System.Net.Mail class to send mail if you are using ASP.NET 2.0 framework.

VB.NET Code Sample

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Net.Mail" %>
<script runat="server">
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim strFrom = "FromAddress@domain.com"
        Dim strTo = "ToAddress@domain.com"
        Dim MailMsg As New MailMessage(New MailAddress(strFrom.Trim()), New MailAddress(strTo))
        MailMsg.BodyEncoding = Encoding.Default
        MailMsg.Subject = "Subject"
        MailMsg.Body = "This is a sample message"
        MailMsg.Priority = MailPriority.High
        MailMsg.IsBodyHtml = True
        'Smtpclient to send the mail message
        Dim SmtpMail As New SmtpClient
        SmtpMail.Host = "localhost"
        SmtpMail.Send(MailMsg)
        lblMessage.Text = "Mail Sent"    
    End Sub
</script>
<html>
<body>
    <form runat="server">
        <asp:Label id="lblMessage" runat="server"></asp:Label>
    </form>
</body>
</html>

C# Code Sample

<%@ Import Namespace="System.Net.Mail" %>
<script language="C#" runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
       //create the mail message
        MailMessage mail = new MailMessage();
        //set the addresses
        mail.From = new MailAddress("fromaddress@domain.com");
        mail.To.Add("toaddress@domain.com");
        //set the content
        mail.Subject = "This is an email";
        mail.Body = "this is the body content of the email.";
        //send the message
         SmtpClient smtp = new SmtpClient("localhost");          smtp.Send(mail);
         lblMessage.Text = "Mail Sent";
    }
</script>
<html>
<body>
    <form runat="server">
        <asp:Label id="lblMessage" runat="server"></asp:Label>
    </form>
</body>
</html>

  • 1 Kasutajad peavad seda kasulikuks
Kas see vastus oli kasulik?

Seotud artiklid

How to configure the ASP.NET 2.0 Membership/Roles Provider to use SQL 2005?

SUMMARYThis article describes how to configure the ASP.NET 2.0...

How to encrypt configuration sections of your web.config using a custom RsaProtectedConfigurationProvider

Details IMPORTANT NOTE: Web.config encryption only works with ASP.NET 2.0.  ...

I get a configuration error when I execute my ASP.NET 2.0 web application.

DETAILSI get the following error when I try to execute my application. Parser Error Message:...

What is a Web Site Administration Tool?

Details The Web Site Administration Tool lets you view and manage the Web site configuration...