[ZT]Sending Mass E-Mails using ASP.NET

Sending Mass E-Mails using ASP.NET
by Faisal Khan.

Overview
This article is part II of a series of articles on sending emails from ASP.NET. In the part I, we learned how to send simple text/html email messages. What that article didn't cover was how to validate user input i.e. what if user enters nothing or enters invalid information in the HTML form input boxes and how to send mass emails to a list of email addresses without the user knowing that the same email has been sent to other users as well.

Why use mass emailing?
Some of the reasons you may want to use mass emailing are:

  • To maintain a newsletter on your web site to keep your web site members informed of any updates or information of interest related to your web site.
  • To send marketing information to a list of subscribers.

How does mass emailing work?
There are lots of techniques of sending mass emails to users. We'll use the first and most basic one known as "Blind Carbon Copying" or simply "BCC". In this technique, the users that receive the email remain unaware ( blind ) of any other users receiving this email. Besides, there can be any number of user emails specified in this field and all of them will receive the email ( should the email gets sent properly ).

The System.Web.Mail.MailMessage class contains a public property known as "BCC". Any emails separated by semicolons ( ';' ) referenced by this field will receive the email. We'll be using this technique in this article.

Why use form validation?
When receiving input from the user through HTML form fields, usually there are certain fields which are *required* and others are optional. For example, In the part I of this article, we asked users to enter information like 'From', 'To', 'MailFormat', 'Subject' and 'Body' in their respective input fields. To successfully complete the transaction we needed all of this information and that ASP.NET script would have failed had you missed any input field.

So how will we validate user input?
We'll make use of built-in ASP.NET validator controls to do all the validation for us. They give us great deal of flexibility in handling input validation, we can specify which fields to be validated, what error message to show if user entered invalid information, the ability to display all the error messages as a list to the user and to proceed if all the information has been validated otherwise wait and display the validation summary to the user.

Brief summary of ASP.NET validator controls
Following is a list of all ASP.NET validator controls:

  1. <asp:RequiredFieldValidator>
    Used for validating input fields which are required.

  2. <asp:RangeValidator>
    Used for making sure that the information provided is within a specific text or numeric range.

  3. <asp:CompareValidator>
    Used for comparing a value in one input field with the one in another.

  4. <asp:RegularExpressionValidator>
    Used for matching the input value with a regular expression.

  5. <asp:CustomValidator>
    Used for custom validation of the user input using a client-side or server-side method.

  6. <asp:ValidationSummary>
    Used for displaying a list of error messages ( if any ) to the user if validation in one or more validation controls failed.

In this article, we'll be making use of <asp:RequiredFieldValidator> control.

SendEmail.aspx
Ok, let's create the new SendEmail.aspx page for part II of this article. Rename the old "SendEmail.aspx" ASP.NET page that you created in part I of this article to some other name ( so that we can create the new and better SendEmail.aspx page for this article ) and create a new "SendEmail.aspx" page in the same folder.

 

Now, copy/paste following code in it:

<!-- SendEmail.aspx -->
<%@ Page Language="vb" AutoEventWireup="false"%>
<%@ Import NameSpace="System.Web.Mail" %>

<script runat="server">
	Protected Sub SendEmail(ByVal sender As Object, ByVal e As EventArgs)
		If IsValid = False Then
			Exit Sub
		End If

		Dim mail As New MailMessage()
		Dim stringArr As String() = GetData()

		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

		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()

		mail.Subject = Request.Form("subject")
		mail.Body = Request.Form("body")

		Try
			SmtpMail.SmtpServer = "localhost"
			SmtpMail.Send(mail)
		Catch ex As Exception
			message.Text = "<span style=""color:red;"">" & _
				ex.Message & "</span>"
			Exit Sub
		End Try

		message.Text = "Message Sent...<br><br><a " & _
			"href=""SendEmail.aspx"">Go Back</a>"
	End Sub

	Protected Function GetData() As String()
		Dim stringArr(3) As String

		stringArr(0) = "youremail1@fakeaddress.com"
		stringArr(1) = "youremail2@fakeaddress.com"
		stringArr(2) = "youremail3@fakeaddress.com"

		Return stringArr

	End Function
</script>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
	<title>Sending E-Mails using ASP.NET ( Part II )</title>
	<style>
	body { background-color:white; }
	body, select { font-family:Verdana; font-size:100%; }
	textarea, input { font-family:Verdana; font-size:100%; }
	.stdInput { width:400; }
	.submit { width:20; height:20; }
	</style>
</head>
<body>

<p align="center">
	<asp:label id="Message" runat="server" />
</p>

<form method="post" runat="server" ID="Form1">
<% If IsPostBack = False Then %>
<p align="center">All fields are required.</p>

<table width="80%" border="0" align="center" cellpadding="2" cellspacing="2">
	<tr>
		<td width="20%" align="right">From : </td>
		<td>
		<input type="text" id="From" class="stdInput" runat="server" />
		<asp:RequiredFieldValidator ID="FromRequired" 
			ControlToValidate="From" 
			ErrorMessage=""From" field is required"
			Display="Dynamic"
			Runat="server" EnableClientScript="false" />
		</td>
	</tr>
	<tr>
		<td align="right">To : </td>
		<td>
		<input type="text" id="To" class="stdInput"
			runat="server" />
		<asp:RequiredFieldValidator ID="ToRequired" 
			ControlToValidate="To" 
			ErrorMessage=""To" field is required"
			Display="Dynamic"
			Runat="server" EnableClientScript="false" />
		</td>
	</tr>
	<tr>
		<td align="right">MailFormat : </td>
		<td>
		<select name="Format">
			<option value="text">Text</option>
			<option value="html">HTML</option>
		</select>
		</td>
	</tr>
	<tr>
		<td align="right">Subject : </td>
		<td>
		<input type="text" id="Subject" class="stdInput"
			runat="server">
		<asp:RequiredFieldValidator ID="SubjectRequired" 
			ControlToValidate="Subject" 
			ErrorMessage=""Subject" field is required"
			Display="Dynamic"
			Runat="server" EnableClientScript="false" />
		</td>
	</tr>
	<tr>
		<td valign="top" align="right">Body : </td>
		<td>
		<textarea cols="5" rows="10" id="Body" class="stdInput"
			runat="server"></textarea>
		<asp:RequiredFieldValidator ID="Requiredfieldvalidator1" 
			ControlToValidate="Body" 
			ErrorMessage=""Body" field is required"
			Display="Dynamic"
			Runat="server" EnableClientScript="false" />
		</td>
	</tr>
	<tr>
		<td> </td>
		<td>
		<input type="submit" OnServerClick="SendEmail" runat="server" 
		class="submit" value=" " ID="Submit1" /> Send Email!
		</td>
	</tr>
</table>

<% Else %>
<asp:ValidationSummary ID="ValSummary"
	HeaderText="<p>Following errors ocurred:</p>"
	ShowSummary="True" DisplayMode="BulletList" EnableClientScript="False"
	ForeColor="black" Runat="server" />
<% End If %>
</form>

</body>
</html>

Explanation
The first line tells that we are going to use VB.NET to write the server-side part of this ASP.NET page. We also import "System.Web.Mail" namespace to make use of SmtpMail and MailMessage classes.

<%@ Page Language="vb" AutoEventWireup="false"%>
<%@ Import NameSpace="System.Web.Mail" %>

Any code here is supposed to run on the server-side.

<script runat="server">
	...
</script>

There are two methods in this ASP.NET page; SendEmail() and GetData(). The GetData() function is supposed to return an array of String objects. These String objects should be email addresses of the users this email will be sent to.

You should replace ( or override ) the code in this function to put ADO.NET code or something to retrieve user emails from your database. To keep things simple we just created a fake array of user email addresses and returned it to the calling method.

Note: Replace these fake email addresses with real ones to receive the emails that'll be sent using this ASP.NET page.
	Protected Function GetData() As String()
		Dim stringArr(3) As String

		stringArr(0) = "youremail1@fakeaddress.com"
		stringArr(1) = "youremail2@fakeaddress.com"
		stringArr(2) = "youremail3@fakeaddress.com"

		Return stringArr

	End Function


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
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 )
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 )
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 )
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.








 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值