Create Your Own Mailing List Server with .NET 2.0

Create Your Own Mailing List Server with .NET 2.0

f you’re a developer, chances are that you’re no stranger to mailing lists. A mailing list contains a group of users who are subscribed to receive regular emails pertaining to a specific topic. Usually, the process is automated?you send an email requesting to be added to a list, and to unsubscribe, you send another email. Mailing lists are often managed by list server software, which you can either buy or purchase as a service. This article demonstrates how to build your own mailing list server, making use of the new classes located in the System.Net.Mail namespace in .NET 2.0, as well as some techniques to retrieve emails from Outlook. For a mailing list server to work, you need to be able to:

  • Send messages to list members
  • Receive subscription/unsubscription email requests from users
  • Automate the process of adding and removing users.

Sending emails is easy with the System.NET.Mail namespace. However, it’s important to realize that this namespace only allows you to send emails; retrieval of emails is not supported. Hence, I’ll show you how to overcome this limitation by “talking” to Outlook instead.

Receiving Emails
As mentioned, the System.NET.Mail namespace does not contain classes to receive emails. This is because reading emails involves much more effort than most people can imagine, and involves parsing the MIME message formats. This means you need to find other ways to read emails from a mail server (unless you want to spend the weekend coding, or spend money on a third-part component).

One good (and readily available) solution is to make use of Outlook?you download all your emails using Outlook and then programmatically access them from within your .NET application. That way, you can leave all the dirty work of communicating with the email server and message parsing to Outlook, and access the emails from Outlook after they have been downloaded.

For this article, you should create a new email account to use as the mailing list alias. For simplicity’s sake, I suggest you create a Gmail account. Using the Gmail account you have created, configure Outlook 2007 (you can also use Outlook 2003) to download mails from this account.

Author’s Note: For instructions on how to configure the Gmail account to work with Outlook, check out the following URL.

Once the account is setup properly, verify that you are able to send and receive mails using Outlook. Once that is done, you are ready to proceed to the next step.

The next step would be for your application to programmatically access the emails located in Outlook. Before you do that, I suggest you go to Tools | Trust Center? and select the “Never warn me about suspicious activity (not recommended)” option (see Figure 1).

Figure 1. No Warning: Enabling programmatic access to Outlook without raising a warning message.
Figure 2. MailingListServer: Populating Form1 with the various controls.

This is because every time your application accesses the mails in Outlook, Outlook will prompt the security warning; you should turn off this warning.

Using Visual Studio 2005, create a new Windows application and name the project MailingListServer. Populate the default Form1 with the following controls (see also Figure 2).

  • Button control
  • Label controls
  • TextBox controls
  • ListBox controls

The top part of the window allows you to send messages to the list members. The bottom left part of the window shows the list of members currently subscribed to your list. The right bottom part shows the messages sent by users to subscribe/unsubscribe to/from the list.

Add a reference to the Microsoft.Office.Interop.Outlook library (see Figure 3).

Figure 3. Add a Reference: Adding a reference to the Outlook interop library.

Switching to the code-behind of Form1, import the following namespaces:

Imports System.DataImports System.Data.SqlClientImports Microsoft.Office.InteropImports System.NetImports System.Net.Mail

Next, declare the constants and member variables shown in Listing 1.

Take special note of the port number for the Gmail’s SMTP server?587. When you configure your Outlook to access Gmail, you use port 465 for the outgoing server. However, you cannot use port 465 for your application as port 465 only works for Outlook. For programmatic access, use port 587.

Next, add a SQL Express database to your project (right-click project name in Solution Explorer and select Add | New Item?). Select SQL Database and use the default name Database1.mdf. Once the database is added to the project, double-click on it to edit it in Server Explorer. Add a table to the database by right-clicking on the Tables item and select Add New Table. The Server Explorer and the completed table (the Users table consists of just a single field named EmailAddress.

Now, define a delegate and a subroutine to update the two ListBox controls (see Listing 2).

Basically, the UpdateStatus() subroutine updates the two ListBox controls?lstUsers and lstQueue. The lstUsers control shows all the email addresses stored in the database. The lstQueue control shows the “subscribe/unsubscribe” email requests sent by users. There will be more discussion of this shortly.

When the form is first loaded, you create an instance of the Outlook.ApplicationClass class so that you can work with the content in Outlook. In addition, you also configure the SMTPClient object so that you can send email messages to users:

Private Sub Form1_Load( _   ByVal sender As System.Object, _   ByVal e As System.EventArgs) _   Handles MyBase.Load   outlookApp = New Outlook.ApplicationClass()   '---set the SMTP Settings---   With SMTPClient      .UseDefaultCredentials = False      .EnableSsl = True      .Credentials = New NetworkCredential(USER_NAME, PASSWORD)   End With   '---update the queue status---   lstQueue.BeginInvoke(New _      MyDelegate(AddressOf UpdateStatus), _      New Object() {})End Sub

When Outlook receives new email messages, the ApplicationClass object will fire the NewMailEx event once for every new email received. The event passes in the EntryIDCollection parameter containing an identifier to the new email message. Here, you will extract the message in this event (see Listing 3).

Note that I have chosen to concatenate the email address of the sender and the subject of the message into a string and then enqueue it into a Queue data structure (see Figure 4). But why not process it immediately? I realized that when Outlook downloads multiple emails in one go, this event will not be fired multiple times if there is a delay in processing this event. Hence, I wanted to free up this event handler as soon as it is fired so that it will continue to fire for the next new message received.

Figure 4. Enqueuing: Saving the subscribe/unsubscribe requests in a queue.
Figure 5. Processing Requests: Configure the Timer control to activate every five seconds.

With the subscribe/unsubscribe request in the queue, when do you process it? For this purpose, you can use a Timer control. Add a Timer control to the form and set its Enable property to True and Interval to 5000 (see Figure 5).

The Timer control’s Tick event will be fired every five seconds and it is in this event that you process the subscribe/unsubscribe requests (see Listing 4).

You will dequeue all the requests stored inside the queue one-by-one and then call the HandleSubscription() subroutine, which is defined in Listing 5.

If the user sends in an email with the subject “subscribe,” you will add the user’s email address into the database and then send him an email using the SendEmail() subroutine (you will define this in the next section). If the email subject is “unsubscribe,” you delete the user from the database.

Sending Emails
Receiving emails is the hard part; sending emails out to users is extremely easy. All you need to send emails is to use a SmtpClient object and a MailMessage object, both from the System.Net.Mail namespace. Some of the methods in the previous section calls the SendEmail() subroutine, which is defined as shown in Listing 6.

If the Email parameter is empty, the code assumes that you want to send an email to all subscribed users; otherwise, it sends the email only to the email address specified in the Email parameter.

Finally, code the Send Message button as follows:

'---sends a message to all subscribers---   Private Sub btnSendMessage_Click( _      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles btnSendMessage.Click      SendEmail(String.Empty, txtSubject.Text, txtMessage.Text)      MsgBox("Message sent!")   End Sub

Testing the Application
Now that you have all the pieces together, let’s put it to test. For this application, you have to ensure that Outlook is running before you run your application.

Send an email to the account that you use for the mailing list server with the subject “subscribe.” After Outlook finishes downloading new emails, it notifies your application (via the NewMailEx event). The request will be queued and shown in the Queue Status ListBox (see left of Figure 6). About five seconds later, the request in the queue will be processed and your email address will be added to the list of subscribed users (see right of Figure 6).

At the same time, the application will automatically send a confirmation email to you, informing you that you have successfully subscribed to the list.

Figure 6. Subscribe: Subscribing a user to the mailing list.
Figure 7. Sending a Message: Sending a message to all subscribed users.

To unsubscribe from the mailing list, simply send an email with the subject “unsubscribe” to the same email account. As the list administrator, to send an email to all subscribed users simply type in the subject and message and click the Send Message button (see Figure 7).

Basic and Useful
The most critical part of implementing a mailing list server is automating the subscribing and unsubscribing process. Of course, you can enhance it further by detecting bounced emails (such as emails account expiring when people change jobs), etc. Let me know if this application is useful to you.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist