The second method is the SendEmail()
. This method will be called by the ASP.NET CLR everytime you press the "Send Email!" button in the HTML form. The code to send email is contained within this method.
Protected Sub SendEmail(ByVal sender As Object, ByVal e As EventArgs)
...
End Sub
The first thing we do in this method is to see if all the validation controls have validated the user input. In other words, is all the input clean? If the user has left some required fields then "IsValid" property will return False
and if it returns False
then we simply exit the sub-routine ( the <asp:ValidationSummary> control will in the mean time display error messages to the user ).
If IsValid = False Then
Exit Sub
End If
If the input has been validated and has found to be "clean" then we move forward. The first thing we do is to create MailMessage
object to encapsulate our email message. We'll be setting some properties of this object later on.
Next we retrieve a list of user email addresses as a String
array by calling the GetData()
method. In this case GetData()
returns a hard-coded array of fake email addresses, in your case you may code GetData()
to return an array of real user email addresses from your database ( i.e. if you want your users to receive this email, otherwise just enter your email address in place of those fake email addresses to test the script ).
Dim mail As New MailMessage()
Dim stringArr As String() = GetData()
We set the "To
" and "From
" properties to the "To" and "From" input field values entered by the user.
Note: The kind of values you should put in "To" and "From" fields will be covered later.
Next we set the "BodyFormat
" property to either "Text" or "HTML" depending on what the user had selected from the drop-down box.
mail.To = Request.Form("to")
mail.From = Request.Form("from")
If Request.Form("format").Equals("text") Then
mail.BodyFormat = MailFormat.Text
Else
mail.BodyFormat = MailFormat.Html
End If
Next we run a For..Next loop to iterate through the String
array of user email addresses and create a long single-line list of email addresses separated by semi-colons.
Dim i As Integer
Dim buffer As New StringBuilder()
For i = 0 To stringArr.Length - 1
If i <> 0 Then
buffer.Append(";")
End If
buffer.Append(stringArr(i))
Next
mail.Bcc = buffer.ToString()
Next we set the "Subject
" and "Body
" properties of the MailMessage
object to the values entered by the user.
mail.Subject = Request.Form("subject")
mail.Body = Request.Form("body")
Lastly, we specify the SMTP server ( change it to your or your ISP's SMTP server ) we want to use.
Note: It is not required to specify an SMTP server because the .NET CLR can call the COM component of the SMTP Service on your system directly to send the email/s, but it is generally not a good idea because it'd be inefficient and the fact that you may get "Could not access 'CDO.Message' object" error if your SMTP Service is stopped or has not been installed properly.
To use your own SMTP Server ( as we have done ), you can start SMTP Service ( SMTPSVC ) if it is not already started by issueing the following command at the Command-Prompt:
net start smtpsvc
Note: SMTP Service only comes installed or can be installed on Win2k and above Windows systems.
We then send the MailMessage
using SmtpMail.Send()
method. If any exceptions are thrown, we catch them and display the exception message to the user.
Try
SmtpMail.SmtpServer = "localhost"
SmtpMail.Send(mail)
Catch ex As Exception
message.Text = "<span style=""color:red;"">" & _
ex.Message & "</span>"
Exit Sub
End Try
If everything has gone on well, we display the "Message Sent..." message to the user.
message.Text = "Message Sent...<br><br><a " & _
"href=""SendEmail.aspx"">Go Back</a>"
Now comes the HTML portion of our "SendEmail.aspx" page. Almost all the HTML and ASP.NET controls have been put between the <form></form> tags. These form tags have a special attribute "runat" set to "server", which means we are going to make use of ASP.NET Web Form controls within our "SendEmail.aspx" page.
<form method="post" runat="server" ID="Form1">
...
</form>
The first thing that comes under the <form> tag is a boolean check for the IsPostBack
property. If the page has not been posted back then display the HTML form to the user. And if the page has been posted back then our SendEmail()
method will be called automatically and emails will be sent to subscribers so we don't need to display the form again, this time we simply display the results of SendEmail()
method to the user.
<% If IsPostBack = False Then %>
' Show the HTML form
...
<% Else %>
' Show the result of SendEmail()
...
<% End If %>
Let's first look at the code that renders the form to the user. All the standard HTML input fields have an extra attribute 'runtat="server"' to make them accessible from other ASP.NET Web Form controls.
Since I had said earlier that we are going to be using validation in our code to make sure that none of the fields are kept empty, we are going to make use of one of the validator controls that ASP.NET makes us available; <asp:RequiredFieldValidator>.
Let's study the different attributes of <asp:RequiredFieldValidator> control. The first one is "ID" attribute whose value should be unique within that ASP.NET page and is used to uniquely identify this control from other controls in that ASP.NET page. Next attribute is "ControlToValidate>, whose value should be the "ID" of the control we want validated, which in our case is "From".
Next attribute is "ErrorMessage" whose value should be a text message that you want displayed to the user if the input could not be validated. Next attribute is "Display" whose value can be 'dynamic' or 'static', use 'static' if you don't want the width of column to change when error message is shown to the user or use 'dynamic' if you don't care :).
Next attribute is "EnableClientScript> which requires a boolean ( true | false ) value. Since I don't want to put JavaScript on my page, I set it to "false". The last attribute 'Runat="Server"' is a *must* attribute for all the ASP.NET controls.
Note: Had I enabled client-side JavaScript, the user could have seen the error messages before the page is posted back to the server and corrected them there and then.
<input type="text" id="From" class="stdInput" runat="server" />
<asp:RequiredFieldValidator ID="FromRequired"
ControlToValidate="From"
ErrorMessage=""From" field is required"
Display="Dynamic"
EnableClientScript="false" Runat="server" />
Since other input fields and their corresponding ASP.NET validator controls are almost the same, I don't discuss them any further.
Once the user inputs some data and posts the page back to the server, all the validator controls validate their respective field values. If some errors are found then there should be an easy way of showing them to the user, right? yes there is, thanks to <asp:ValidationSummary> control.
Like most other ASP.NET controls, "ID" and "Runat" attributes are required. The "HeaderText" attribute's value should be the header of the message displayed to the user. The "ShowSummary" attribute asks for a boolean value asking for our permission that whether it should display error messages to the user or keep quiet, here we give it the permission to display error messages. The "DisplayMode" attribute allows us to choose the style of output for the error messages, three types of values are accepted; List
, BulletList
, SingleParagraph
.
Next attribute is "EnableClientScript", we disallow client-side JavaScript like we disallowed for other validator controls. Last attribute is "ForeColor", it's value should be the color of text displayed to the user for the error messages, default color is red. I used black just to show that you can change the fore-color property of the font used.
<asp:ValidationSummary ID="ValSummary"
HeaderText="<p>Following errors ocurred:</p>"
ShowSummary="True" DisplayMode="BulletList" EnableClientScript="False"
ForeColor="black" Runat="server" />
We are now done studying the code, save the "SendEmail.aspx" page and run it in your browser. You should some thing like this:
SendEmail.aspx
Now enter some values in the form like shown below.
Note: You can either enter only email addresses in the "From" and "To" fields like "yourname@yoursite.com" or you can also enter sender's and receiver's name which will be shown in the user email receiving program e.g. Outlook Express, like "Sender Name <sender@somemail.com>". First you should type the name and then the email address between < and > tags.
SendEmail.aspx ( After entering some data )
Before hitting the "Send Email!" button make sure SMTP service is running on your system ( if you used 'localhost' as your SMTP server ) by running following command at command-prompt:
net start smtpsvc
Note: If you have set
SmtpMail.SmtpServer
property to your ISP's mail server and you are connected to the internet, then starting SMTP service on your own system is not required.
If all goes well you shold see something like this:
SendEmail.aspx ( After post back, Success message )
To see how the validation controls work, do not enter any data in the form and hit the 'Submit' button again to see a list of error messages displayed like this:
SendEmail.aspx ( After post back, Error message )
Now it is time to receive emails that have just been sent to verify that everything worked correctly.
Note: If you specified multiple email addresses which are aliases to a real email address then you'll receive emails only on real email address accounts e.g. If you have three email addresses on your mail server like mail1@yourmail.com, mail2@yourmail.com and mail3@yourmail.com, all of which are aliases ( redirect the email to ) of yourname@yourmail.com email address, then you will receive a single email message ( not three ) at yourname@yourmail.com.
Summary
In part II of a series of articles on sending emails using ASP.NET, we learned how to send mass emails to users without making their email addresses available to other users using 'Blind Carbon Copying'. We also learned what are validation controls and how to make use of them.
After reading this article and thoroughly studying it's code, you should be ready to build a mass email system for your web site ( or company ).
In future articles we will learn more about other techniques of mass emailing with lot more features like putting user names in the emails and offering the capability to unsubscribe/subscribe.