One of the most commonly performed operations that I see in web applications - aside from database actions - is sending email from code. In Active Server Pages 3.0 and earlier, this task required the use of a third-party control such as ASPMail (from ServerObjects) or ASPEmail (from Persits). Both of these COM objects work quite well, but they are no longer required when dealing with ASP.Net
The only real "requirements" are for the .Net framework and the Microsoft SMTP service to be installed on the web server. After that you can "just do it". Below is a sample page that presents a form to the user and allows them to specify the To, From, Subject, and Body of an email message, then sends the email when the "Send" button is clicked.
01: <%@page language="VB" %>
02: <%@Import Namespace="System.Web.Mail" %>
05: <SCRIPT LANGUAGE="VB" RUNAT="server">
07: Sub SendMail (Obj As Object, E As EventArgs)
09: Dim mailObj AS new MailMessage
11: mailObj.From = MsgFrom.text
12: mailObj.To = MsgTo.Text
13: mailObj.Subject = MsgSubject.Text
14: mailObj.Body = MsgBody.Text
16: SmtpMail.SmtpServer = "localhost"
18: End Sub
21: <form runat="server">
24: <td>Send To:</td>
25: <td><asp:Textbox id="MsgTo" runat="server"/></td>
28: <td>Send From:</td>
29: <td><asp:Textbox id="MsgFrom" runat="server"/></td>
32: <td>Message Subject:</td>
33: <td><asp:Textbox id="MsgSubject" runat="server"/></td>
36: <td>Message Body:</td>
37: <td><asp:Textbox TextMode="multiline" Rows="5" id="MsgBody" runat="server"/></td>
40: <td> </td>
41: <td><asp:button Text="Send" onclick="SendMail" id="Send" runat="server"/></td>
Lines 20 through 43 are just some standard ASP.Net HTML controls that are used to generate an HTML form for the user. One the "Send" button on the form is clicked, the code in the
SendMail subroutine (starting on line 07) is executed.
The first line in the subroutine creates a
MailMessage object. This object is available to our script because we have included a reference to the "
System.Web.Mail" namespace as noted on line 02. This object basically mirrors the options of a standard email message, so the naming is very intuitive. In lines 11 through 14 we set the properties of the new
MailMessage object based on the values from the form variables. Once the properties are set, we only need to call
SmtpMail.Send, as noted on line 16, to execute the delivery of the mail message.
There are other properties that you can set, such as the message priority, whether it should be text or HTML, and the encoding type. More information about these additional properties should be available in the ASP.Net framework documentation.