Recipe 21.8. Sending Mail


Problem

You want the user of your application to be able to send email.

Solution

Create a form to allow the user to enter the email information. When the user submits the form to the server, build a MailMessage object from the email information and then send the email using the SmtpClient class.

In the .aspx file:

  1. Create a form to capture the sender's email address, the recipient's email address, the subject, and the message.

  2. Add a Send button that initiates the sending of the email.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Create a MailMessage object, which is used as a container for the mail message, setting the sender email address, recipient email address, subject, and body using the constructor parameters.

  2. Create a SmtpClient object setting the email server using the constructor parameter.

  3. Call the Send method to perform the send operation.

Examples 21-18, 21-19 through 21-20 show the .aspx file and the VB and C# code-behind files for an application we've written to demonstrate this solution. The output of the application is shown in Figure 21-6.

Discussion

Sending email is a common requirement in web applications. In classic ASP, third-party controls are required to send email. In ASP.NET, all of the functionality required to send email is provided and is very easy to use.

Figure 21-6. Send email form output


To send email, you need the sender's email address, the recipient's email address, the subject, and the message. In our example that illustrates this solution, a form is used to collect the information. The form includes a Send button that initiates the sending of the email.

When the Send button is clicked, the btnSend_ServerClick method in the code-behind is executed. This method is responsible for collecting the information from the form and sending the email. For simplicity, no validation is performed on the data in our example; however, you should provide validation of the data in your application. Refer to Chapter 3 for data validation examples.

The first step in sending an email is to create a MailMessage object. This object is used as a container for the mail message, as shown in our example. The sender email address, recipient email address, subject, and message body are set using the constructor parameters.

The sender email address, recipient email address, and subject should always be set to valid values. Spam filters typically check these fields, and, if any are blank, the mail message may be branded as spam. In addition, some spam filters check the format of the recipient email address, and the more thorough spam filters will verify if the sender email address is valid.


After the MailMessage is initialized, a SmtpClient object is created setting the email server that will send the email message using the constructor parameter and the Send method will be called to perform the send operation.

In Version 2.0 of the .NET Framework, a new namespace (System.Net.Mail) has been added to provide support for sending email. The classes provided in System.Web.Mail in Version 1.x have been deprecated and should not be used for new applications. They are still provided to support applications developed for 1.x, though.


Our example shows the case of an email sent to a single recipient. To send the email to multiple recipients, add the recipient email addresses to the To collection property.

Copies and blind copies can be sent by adding the email address of the copied recipients to the CC collection property and the email address of the blind copy recipient to the Bcc collection property.

Attachments can be included with the email by adding MailAttachment objects to the Attachments collection, as shown here, where [filename] is the fully qualified path to the file that you need to attach to the mail message:

 

emailMessage.Attachments.Add(New Attachment([filename]))

emailMessage.Attachments.Add(new Attachment([filename]));

See Also

Chapter 3 for data validation

Example 21-18. Sending email (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH21SendingEmailVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH21SendingEmailVB" Title="Sending Email" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > Sending Email (VB) </div> <table width="60%" align="center" border="0"> <tr> <td width="50%" align="right" >Sender Email: </td> <td width="50%"> <input  runat="server" /> </td> </tr> <tr> <td width="50%" align="right" >Recipient Email: </td> <td width="50%"> <input  runat="server" /> </td> </tr> <tr> <td width="50%" align="right" >Subject: </td> <td width="50%"> <input  runat="server" /> </td> </tr> <tr> <td width="50%" align="right" >Message: </td> <td width="50%"> <textarea  runat="server" rows="4" cols="20"></textarea> </td> </tr> <tr> <td colspan="2" align="center"> <br /> <input  runat="server" type="button" value="Send" onserverclick="btnSend_ServerClick" /> </td> </tr> </table> </asp:Content> 

Example 21-19. Sending email code-behind (.vb)

 Option Explicit On  Option Strict On Imports System Imports System.Net.Mail Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code-behind for ''' CH21SendingEmailVB.aspx ''' </summary> Partial Class CH21SendingEmailVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load End Sub 'Page_Load '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the send button click ''' event. It is responsible for sending an email based on the data ''' entered on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnSend_ServerClick(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim emailMessage As MailMessage Dim emailAttachement As Attachment Dim filename As String Dim client As SmtpClient Dim emailServer As String 'build the mail message with an attachment emailMessage = New MailMessage(txtSenderEmail.Value, _    txtRecipientEmail.Value, _    txtSubject.Value, _    txtMessage.Value) 'add an attachment filename = Server.MapPath("downloads") & "\SampleEmailAttachment.txt" emailAttachement = New Attachment(filename) emailMessage.Attachments.Add(emailAttachement) 'get the email server and send the email emailServer = ConfigurationManager.AppSettings("EmailServer") client = New SmtpClient(emailServer) client.Send(emailMessage) End Sub 'btnSend_ServerClick End Class 'CH21SendingEmailVB End Namespace 

Example 21-20. Sending email code-behind (.cs)

 using System;  using System.Configuration; using System.Net.Mail; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code-behind for /// CH21SendingEmailCS.aspx /// </summary> public partial class CH21SendingEmailCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { } // Page_Load ///*********************************************************************** /// <summary> /// This routine provides the event handler for the send button click /// event. It is responsible for sending an email based on the data /// entered on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnSend_ServerClick(Object sender,   System.EventArgs e) { MailMessage emailMessage; Attachment emailAttachement; String filename; SmtpClient client; String emailServer; // build the mail message with an attachment emailMessage = new MailMessage(txtSenderEmail.Value,    txtRecipientEmail.Value,    txtSubject.Value,    txtMessage.Value); // add an attachment filename = Server.MapPath("downloads") + "\\SampleEmailAttachment.txt"; emailAttachement = new Attachment(filename); emailMessage.Attachments.Add(emailAttachement); // get the email server and send the email emailServer = ConfigurationManager.AppSettings["EmailServer"]; client = new SmtpClient(emailServer); client.Send(emailMessage); } //btnSend_ServerClick } // CH21SendingEmailCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net