Sending Emails in ASP.NET

One of the features that is frequently required of a web site is the ability to send emails.  This can be for simple confirmation of account details, administrative purposes, etc.  It’s fairly straight forward and in this article I’ll detail how to send emails from your web pages.

In this article, the tutorial assumes that you know your ISP’s SMTP server address.  Some versions of IIS ship with a built in SMTP server, but not Vista or Windows 7, so using the built in IIS Server will be the subject of another tutorial.

ASP.NET 2.0 provides two important classes within the System.Net.Mail namespace, that we can work with to send email.

The 2 classes that we use are:

1. MailMessage - to create our email message object and assign properties such as From, To, Subject and Body
2. SmtpClient - to create our SMTP client object, set the details of our STMP server and send our created MailMessage Object to a SMTP Server

The simplest ‘sure fire’ method of sending an email via your ISP’s mail server is listed below in the code below for our file 'ExternalMailServer.aspx'. The page below creates a simple form with a couple of textboxes and a send button, as well as a label controls.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ExternalMailServer.aspx.vb"
 Inherits="ExternalMailServer" %>
<!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>Send Email</title>
  </head>
  <body>
  
   <form id="form1" runat="server">
   <div>
    <asp:Label ID="lblSendTo" runat="server" Text="Send To"></asp:Label>
    <asp:TextBox ID="SendTo" runat="server"></asp:TextBox>
    <br />
    <asp:Label ID="lblMessage" runat="server" Text="Message"></asp:Label>
    <asp:TextBox ID="Message" runat="server"></asp:TextBox>
    <br />
    <asp:Button ID="Sendbutton" runat="server" Text="Send" />
   <br />
   <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>  
   </div>
  </form>
  
  </body>
  </html>
  

Below is our codebehind file ‘ExternalMailServer.aspx.vb’. The first thing we do is import the namespace System.Net.Mail so we can access and reference the classes we need.

Imports System.Net.Mail

Partial Class ExternalMailServer

   Inherits System.Web.UI.Page
   
   Protected Sub Sendbutton_Click(ByVal  sender As Object, ByVal e As System.EventArgs) _
   Handles Sendbutton.Click
   
   Dim sMailServer As String  = "Your ISP Server"
   Dim sUserName As String  = "Your User Name"
   Dim sPassword As String  = "Your Password"
   Dim sFrom As String  = "Your Email Address"
   
   'Create a message object and pass the origin  and email address and
   'Destination email address in as parameters.
   Dim oMessage As New MailMessage(sFrom, SendTo.Text.Trim())
   'Set the subject of the mail message
   oMessage.Subject = "Mail from Web Page"
   'Set the body of the message - make it HTML
   oMessage.IsBodyHtml = True
   oMessage.Body = Message.Text
   'Build the Credential object
   Dim oAuthInfo As New System.Net.NetworkCredential(sUserName, sPassword)
   'Create our SMTPClient object, set the mail server, and auth items
   Dim oClient = New SmtpClient()
   oClient.Host = sMailServer
   oClient.UseDefaultCredentials = False
   oClient.Credentials =  oAuthInfo
   'Send the message
   oClient.Send(oMessage)
   
   lblStatus.Text  = "Mail sent - give it a few minutes and  check!"

   End  Sub
End Class

Note that to make this work you will need to put your own details in to the Sendbutton_Click method to access your SMTP server.  This routine also assumes that your Mail Server is operating on Port 25, the usual Port for the SMTP service.  In order to improve security, some servers are operated on different Port numbers, such as 26.  If this is the case then simply add the oClient.Port=<Port Number> as below:

 'Create our SMTPClient object, set the mail server, and auth items
  Dim oClient = New SmtpClient()
  oClient.Host = sMailServer
  oClient.Port = 26
  oClient.UseDefaultCredentials = False
  oClient.Credentials =  oAuthInfo

Credentials

We set up a NetworkCredential object in this code using your username and password to validate your use of the server.  Should your SMTP server NOT require this sort of validation, then remove the oClient.Credentials = oAuthInfo line.

HTML Mail

If you wish to send only text mails to your recipients, then set the IsBodyHtml property of the MailMessage object to false.  This will remove HTML formatting from the mail.

Sending an Attachment

The final thing we’ll take a look at here is how to send an attachment by email.  This is done by the button code listed below.  For the sake of the demonstration I’m sending the web.config file of the site.

Imports System.Net.Mail

Protected Sub Sendbutton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Sendbutton.Click
   
   Dim sMailServer As String = "Your ISP  Server"
   Dim sUserName As String  = "Your User Name"
   Dim sPassword As String  = "Your Password"
   Dim sFrom As String  = "Your Email Address"
   'Create a message object and pass the origin and email address and
   'Destination email address in as parameters.
   Dim oMessage As New  MailMessage(sFrom, SendTo.Text.Trim())
   'Set the subject of the mail message
   oMessage.Subject = "Mail from Web Page"
   'Now the attachment.  Attached the web.config file as a different file type!
   Dim oAttch As New Attachment("C:\Data\Development\DevelopmentProjects\MailDemos\web.config")

   oMessage.Attachments.Add(oAttch)

   'Set the body of the message - make it plain  text for a change
   oMessage.IsBodyHtml = False
   oMessage.Body = Message.Text
   'Build the Credential object
   Dim oAuthInfo As New System.Net.NetworkCredential(sUserName,  sPassword)
   'Set the mail server, and auth items
   Dim oClient = New SmtpClient()
   oClient.Host = sMailServer
   oClient.UseDefaultCredentials = False
   oClient.Credentials = oAuthInfo
   'Send the message
   oClient.Send(oMessage)
 
   lblStatus.Text  = "Mail sent - give it a few minutes and  check!"
   
End Sub

And that’s that, the code listed here isn’t ‘production quality’, it could do with some error trapping and general tidying up, but it demonstrates the principles of sending mail from your web pages.

Setting the SMTP object Properties in the Web.Config

Rather than set the SMTP object properties in your code, you can set them application wide in your web.config. In your code you just create a new instance of the SMTPClient class (displayed in the second box below) and then just use the Send method.

<system.net>
<mailSettings>
<smtp from="test@youremail.com">
<network host="smtp.server.com" port="25" userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
 Dim oClient = New SmtpClient()
  'Send the message
 oClient.Send(oMessage)

Get the best asp web hosting provider now and save 30%

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Free ASP Hosting