Click here to Skip to main content
Licence CPOL
First Posted 24 May 2007
Views 60,084
Downloads 302
Bookmarked 70 times

SuperMail.NET, a bulk emailing app using System.Net.Mail, MS Access, and My.Settings

By | 12 Aug 2007 | Article
Using the System.Net.Mail namespace, My.Settings, and MS Access to develop a bulk emailing application.

Introduction

SuperMail.NET is a bulk emailing application written in VB.NET using System.Net.Mail, MS Access, and My.Settings. It is still not completely finished, but it has come a long way from the time I first posted this article. Even though it's not finished, I have decided to do the update anyway because I think there are some good samples here for anyone interested in System.Net.Mail. I use this app at work all the time for the HTML newsletters I send out to clients. You can download the source code above and use SuperMail.NET as well; however, I would recommend running it in an IDE as I have not yet added all the exception handling.

What SuperMail.NET does is allow you to store your newsletters or HTML emails on your web server in the form of .htm files, and then scrape the HTML replacing any specified text (the recipient name, date, etc..), and then send them out to a list you import into an Access database using field mapping.

Before we look at the code, here are a couple of bullets listing what this article covers, for quick reference:

  • Using the System.Net.Mail namespace to send email with Visual Basic .NET 2005
  • How to scrape HTML from a web page using System.Net.WebRequest in Visual Basic .NET 2005
  • How to save user settings in the app.config file using My.Settings in Visual Basic .NET 2005
  • Looping through a DataGridView in Visual Basic .NET 2005

Using the Code

This is the sub routine I am using to create and send the emails. Notice that I am scraping the HTML, replacing the recipient name, and then inserting it into the body of the email. Also, I reference My.Settings for the settings that were entered by the user for everything else (sending email account, port number, subject line, credentials, etc.). The If statements are looking to see if the user specified to use credentials or SSL.

' Sub to send the email(s)
Private Sub SendEmail( ByVal emailAddress As String, _
                       ByVal name As String)

    ' start showing wait cursor while email(s) are being sent
    Me.Cursor = Cursors.WaitCursor
    'scrape site and incert strRecName
    Dim strMailBody As String = ScreenScrapeHtml(CStr(cbSelectEmail.Text))
    strMailBody = strMailBody.Replace("SoNso", name)
    'create the mail message
    Dim mail As New System.Net.Mail.MailMessage()
    'set the addresses
    mail.From = New System.Net.Mail.MailAddress(my.Settings.EmailAccount)
    mail.To.Add(emailAddress)
    'set the content
    mail.IsBodyHtml = True
    mail.Subject = CStr(cbEmailSubject.Text)
    mail.Body = strMailBody
    'send the message(s)
    Dim smtp As New System.Net.Mail.SmtpClient(CStr(My.Settings.SMPT))
    'Set the port number to use
    smtp.Port = My.Settings.Port
    'Set credentials if checked
    If My.Settings.UseAuthentication = True Then
        smtp.Credentials = New System.Net.NetworkCredential( _
        My.Settings.UserName, My.Settings.Password)
    End If
    'enable ssl if checked
    If My.Settings.SSL = True Then
        smtp.EnableSsl = True
    End If
    ' send 
    smtp.Send(mail)
    ' Stop wait cursor
    Me.Cursor = Cursors.Arrow
End Sub

This is the function I use to scrape the HTML from the server and put it into a variable:

' Function to get HTML to put into email body
Public Function ScreenScrapeHtml( ByVal url As String) As String

    Dim objRequest As System.Net.WebRequest = _
        System.Net.HttpWebRequest.Create(url)
    Dim sr As New IO.StreamReader(objRequest.GetResponse().GetResponseStream())
    Dim result As String = sr.ReadToEnd()
    sr.Close()
    Return result
End Function 'ScreenScrapeHtml

This is the code I use to send an individual email, or loop through the DataGrigView and send out the entire list. I think my current technique for looping through the items works fine for now, but I am looking to change it so it will identify the column headers to grab the correct fields. This way, once I have it worked out, you can import lists directly from the application. It won't mater how many columns are in the DataGridView as long as the headers are named correctly. I am still trying to decide the best way to do it. This does, however, show one way to do it, and can be modified to fit individual needs.

' Send out email(s) on send button click event
Private Sub btnSend_Click( ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnSend.Click

    ' send only one email
    If ckbSend1.Checked = True Then
        Dim strEmail As String = txtToAddress.Text
        Dim strName As String = txtRecName.Text
        SendEmail(strEmail, strName)
    End If

    ' Loop through DataGridView and send all
    If ckbSendAll.Checked = True Then
        Dim strName As String
        Dim strEmail As String
        Dim i As Integer = 0
        For Each row As DataGridViewRow In DataGridView1.Rows
            strName = CStr(DataGridView1.Item(1, i).Value)
            strEmail = CStr(DataGridView1.Item(2, i).Value)
            If strName = "" Then
                Exit For
            End If
            SendEmail(strEmail, strName)
            i += 1
        Next
    End If
    MessageBox.Show("Your message(s) have beed sent!")
End Sub

This class is for a tool I created to save user settings to My.Settings. It is accessible from the menu strip, and is one of three I have built so far. There is also one for saving URLs for up to five different HTML emails, and one for saving subject lines. I only put up the code for this one because they all pretty much work the same way. You would need to first right click on the project properties and add the settings. You would want to use user settings as they are readable and writable, whereas application settings are read only. It's a pretty straightforward process, and I found it to be extremely useful in this case. You don't even have to edit the XML in app.config; Visual Studio does everything for you. Once you add the settings in the project properties, you can immediately read from them, and write to them, as shown below:

Imports System.Windows.Forms

Public Class UserSettings

Private Sub OK_Button_Click( ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles OK_Button.Click

    ' Save setings
    My.Settings.EmailAccount = txtUserEmail.Text
    My.Settings.SMPT = txtSMTP.Text
    If ckbUseAuthentication.Checked = False Then
        My.Settings.UseAuthentication = False
        txtUserName.Enabled = False
        txtPassword.Enabled = False
    End If

    If ckbUseAuthentication.Checked = True Then
        My.Settings.UseAuthentication = True
        My.Settings.UserName = txtUserName.Text
        My.Settings.Password = txtPassword.Text
    End If

    If ckbSSL.Checked = True Then
        My.Settings.SSL = True
    Else
        My.Settings.SSL = False
    End If

    My.Settings.Port = CInt(txtPortNumber.Text)
    Me.Refresh()
    MessageBox.Show("Saved")
End Sub

Private Sub Cancel_Button_Click( ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Cancel_Button.Click

    Me.DialogResult = System.Windows.Forms.DialogResult.Cancel

    'Close Tool
    Me.Close()
End Sub

Private Sub UserSettings_Load( ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

    ' Loads current Settings into textBoxes
    txtUserEmail.Text = My.Settings.EmailAccount
    txtSMTP.Text = My.Settings.SMPT

    If My.Settings.UseAuthentication = False Then
        ckbUseAuthentication.Checked = False
        txtUserName.Enabled = False
        txtPassword.Enabled = False
    End If

    If My.Settings.UseAuthentication = True Then
        ckbUseAuthentication.Checked = True
        txtUserName.Text = My.Settings.UserName
        txtPassword.Text = My.Settings.Password
    End If

    If My.Settings.SSL = True Then
        ckbSSL.Checked = True
    Else
        ckbSSL.Checked = False
    End If

    txtPortNumber.Text = My.Settings.Port
End Sub

Private Sub ckbUseAuthentication_CheckedChanged( ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles ckbUseAuthentication.CheckedChanged

    ' Enables.Disables TextBoxes for credentials
    If ckbUseAuthentication.Checked = True Then
        txtUserName.Enabled = True
        txtPassword.Enabled = True
    End If

    If ckbUseAuthentication.Checked = False Then
        txtUserName.Enabled = False
        txtPassword.Enabled = False
    End If
End Sub
End Class

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

AdamNThompson

Web Developer

United States United States

Member

I am a .NET Developer for company that builds custom web applications. It's an interesting job because each site is different. We build anything that the mind can imagine, and the client can afford.
 
Fun stuff... Smile | :)
 
CP is my favorite site for code samples, news, and articles. I like the community here and I like the fact that it mainly caters to developers using the .NET platform.
 
I also write a blog on .NET Development
adam-thompson.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 PinmemberAndreas Saurwein Franci Gonçalves2:05 25 Jan '11  
GeneralI cant download PinmemberMaheshwaran Deveraj3:26 11 Aug '08  
QuestionAttachments?? Pinmemberdherrmann6:40 16 Aug '07  
AnswerRe: Attachments?? Pinmemberfr33l0ad3r11:12 16 Aug '07  
GeneralError Syntax error. Pinmemberbigshervin21:35 17 Jul '07  
GeneralRe: Error Syntax error. Pinmemberfr33l0ad3r3:54 18 Jul '07  
GeneralImages in Supermail.net Pinmemberreldes5:57 17 Jul '07  
GeneralRe: Images in Supermail.net Pinmemberfr33l0ad3r8:30 17 Jul '07  
GeneralRe: Images in Supermail.net Pinmemberreldes11:23 17 Jul '07  
GeneralRe: Images in Supermail.net [modified] Pinmemberfr33l0ad3r11:34 17 Jul '07  
GeneralGood work! Pinmembercommandant_.23:10 16 Jun '07  
GeneralRe: Good work! [modified] Pinmemberfr33l0ad3r5:43 17 Jun '07  
GeneralRe: Good work! Pinmemberlandrovertoo16:52 13 Aug '07  
GeneralRe: Good work! Pinmemberfr33l0ad3r17:47 13 Aug '07  
GeneralMinor Suggestion: Use string.empty Pinmemberrichardkline1:29 16 Jun '07  
GeneralRe: Minor Suggestion: Use string.empty Pinmemberfr33l0ad3r1:36 16 Jun '07  
QuestionHTML mails? PinmemberJohnny J.12:31 3 Jun '07  
AnswerRe: HTML mails? PinmemberKnotBeer4:34 4 Jun '07  
GeneralRe: HTML mails? PinmemberJohnny J.5:40 4 Jun '07  
GeneralRe: HTML mails? PinmemberKnotBeer5:55 4 Jun '07  
GeneralTip PinmemberJared James Sullivan12:35 1 Jun '07  
GeneralSending E-mail with gmail [The easy way] Pinmemberyulyos22:42 28 May '07  
GeneralUse the StringBuilder class instead the System.String and the += operator PinmemberT-luv7:02 24 May '07  
GeneralRe: Use the StringBuilder class instead the System.String and the += operator PinmemberBuaziz20:49 28 May '07  
GeneralRe: Use the StringBuilder class instead the System.String and the += operator Pinmemberjubjubjub5:00 29 May '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 12 Aug 2007
Article Copyright 2007 by AdamNThompson
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid