Recipe 18.7 Sending Mail

     

18.7.1 Problem

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

18.7.2 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 SmtpMail 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.

  2. Set the To , From , Subject , and Body properties to the data entered on the form.

  3. Set the SmtpServer property of the SmtpMail class to the server that will send the email, and then call the Send method to perform the send operation.

Example 18-18 through Example 18-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 18-6.

Figure 18-6. Send mail form output
figs/ancb_1806.gif

18.7.3 Discussion

Sending email is a common requirement in ASP.NET 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.

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 simple 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 2 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.

After creating the MailMessage object, the To , From , Subject , and Body properties need to be set to the data entered on the form.

The To , From , and Subject properties 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 From address, and the more thorough spam filters will verify whether the From address is valid.


After the MailMessage is initialized , the SmtpServer property of the SmtpMail class is set to the server that will send the email, and then the Send method is called to perform the send operation. The SmtpServer property and the Send method are shared (static); therefore, it is not necessary to instantiate a SmtpMail object.

Our example shows the very simple case of an email sent to a single recipient. To send the email to multiple recipients, set the To property to a semicolon-delimited string containing the email addresses of all of the required recipients.

Copies and blind copies can also be sent by setting the Cc property to the email address of copied recipients and the Bcc property to the email address of blind copy recipients. Like the To property, use a semicolon-delimited list for multiple recipients.

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:

 
figs/vbicon.gif
 mail.Attachments.Add(New MailAttachment(   [filename]   )) 
figs/csharpicon.gif
 mail.Attachments.Add(new MailAttachment(   [filename]   )); 

18.7.4 See Also

Chapter 2 for data validation

Example 18-18. Sending email (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="CH18SendingEmailVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH18SendingEmailVB" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Sending Email</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmSendEmail" method="post" runat ="server" > <table width="100%" cellpadding ="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Sending Email (VB) </td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td> <table width="60%" align="center" border="0"> <tr> <td width="50%" align="right">Sender Email: </td> <td width="50%">  <input id="txtSenderEmail" runat="server"></td>  </tr> <tr> <td width="50%" align="right">Recipient Email: </td> <td width="50%">  <input id="txtRecipientEmail" runat="server"></td>  </tr> <tr> <td width="50%" align="right">Subject: </td> <td width="50%">  <input id="txtSubject" runat="server"></td>  </tr> <tr> <td width="50%" align="right">Message: </td> <td width="50%">  <textarea id="txtMessage" runat="server" rows="4" ></textarea>  </tr> <tr> <td colspan="2" align="center"> <br />  <input id="btnSend" runat="server"   type="button" value="Send" />  </td> </tr> </table> </td> </tr> </table> </form> </body> </html> 

Example 18-19. Sending email code-behind (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name : CH18SendingEmailVB.aspx.vb ' ' Description: This module provides the code behind for the ' CH18SendingEmailVB.aspx page ' '***************************************************************************** Imports System Imports System.Web.Mail Namespace ASPNetCookbook.VBExamples Public Class CH18SendingEmailVB Inherits System.Web.UI.Page 'controls on the form Protected txtSenderEmail As System.Web.UI.HtmlControls.HtmlInputText Protected txtRecipientEmail As System.Web.UI.HtmlControls.HtmlInputText Protected txtSubject As System.Web.UI.HtmlControls.HtmlInputText Protected txtMessage As System.Web.UI.HtmlControls.HtmlTextArea Protected WithEvents btnSend As System.Web.UI.HtmlControls.HtmlInputButton '************************************************************************* ' ' ROUTINE: Page_Load ' ' DESCRIPTION: This routine provides the event handler for the page load ' event. It is responsible for initializing the controls ' on the page. '------------------------------------------------------------------------- Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load End Sub 'Page_Load '************************************************************************* ' ' ROUTINE: btnSend_ServerClick ' ' DESCRIPTION: 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. '-------------------------------------------------------------------------  Private Sub btnSend_ServerClick(ByVal sender As Object, _   ByVal e As System.EventArgs) _   Handles btnSend.ServerClick   Dim mail As MailMessage   'create email object   mail = New MailMessage   mail.To = txtRecipientEmail.Value   mail.From = txtSenderEmail.Value   mail.Subject = txtSubject.Value   mail.Body = txtMessage.Value   'mail.Attachments.Add(New MailAttachment("D:\ASPNetBook\notes.txt"))   'send the mail   SmtpMail.SmtpServer = "mail. adelphia .net"   SmtpMail.Send(mail)   End Sub 'btnSend_ServerClick  End Class 'CH18SendingEmailVB End Namespace 

Example 18-20. Sending email code-behind (.cs)
 //---------------------------------------------------------------------------- // // Module Name: CH18SendingEmailCS.aspx.cs // // Description: This module provides the code behind for the // CH18SendingEmailCS.aspx page // //**************************************************************************** using System; using System.Web.Mail; namespace ASPNetCookbook.CSExamples { public class CH18SendingEmailCS : System.Web.UI.Page { // controls on the form protected System.Web.UI.HtmlControls.HtmlInputText txtSenderEmail; protected System.Web.UI.HtmlControls.HtmlInputText txtRecipientEmail; protected System.Web.UI.HtmlControls.HtmlInputText txtSubject; protected System.Web.UI.HtmlControls.HtmlTextArea txtMessage; protected System.Web.UI.HtmlControls.HtmlInputButton btnSend; //************************************************************************ // // ROUTINE: Page_Load // // DESCRIPTION: This routine provides the event handler for the page // load event. It is responsible for initializing the // controls on the page. //------------------------------------------------------------------------ private void Page_Load(object sender, System.EventArgs e) { // wire the send button click event this.btnSend.ServerClick += new EventHandler(this.btnSend_ServerClick); } //************************************************************************ // // ROUTINE: btnSend_ServerClick // // DESCRIPTION: 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. //------------------------------------------------------------------------  private void btnSend_ServerClick(Object sender,   System.EventArgs e)   {   MailMessage mail = null;   // create email object   mail = new MailMessage( );   mail.To = txtRecipientEmail.Value;   mail.From = txtSenderEmail.Value;   mail.Subject = txtSubject.Value;   mail.Body = txtMessage.Value;   // mail.Attachments.Add(new MailAttachment("D:\\ASPNetBook\\notes.txt"));   // send the mail   SmtpMail.SmtpServer = "mail.adelphia.net";   SmtpMail.Send(mail);   } //btnSend_ServerClick  } // CH18SendingEmailCS } 



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

Similar book on Amazon

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