Site Search:
Sign in | Join | Help
4Penny.net

ASP.NET

Notes, Tricks and Tips on ASP.NET Coding

Sending Email from a Contact Page

We set up many basic websites for people and have found ourselves reproducing the same code many times.  Typically we are given a basic html website created by our artists with a non-functional "contact us" page.

We would then copy all of the files into a visual studio solution and create a new contact page.  In the code behind, we would pull the individual form fields and build an email message.  We would then send it through our local mail server.

To speed up development time a bit, we created a dll that will send the email in one line of code.  Add this to the load event of the contact page:

If IsPostBack Then
    Dim mail As New SendMail(Request, Response, "to-address@email.com", "from-address@website.com", "emailServerName", "thankyou.html")
End If

We pass the Request object so that the dll can get the form fields, ie Request.Form("FirstName").  The Response object is passed so that the dll can redirect to the thankyou page.

Here is the code for the dll:

 Imports System.Web
Imports System.Web.UI.Page
Imports System.Collections.Specialized
Imports System.Collections.Generic
Imports System.Net.Mail


Public Class SendMail


    'remove access to the default constructor
    Private Sub New()


    End Sub


    Public Sub New(ByVal r As HttpRequest, ByVal resp As HttpResponse, ByVal ToAddress As String, ByVal FromAddress As String, ByVal EmailServer As String, ByVal RedirectLocation As String)


        Dim fields As List(Of String) = LoadFormFields(r.Form)
        sendEmail(BuildEmail(ToAddress, FromAddress, "Website Form", fields), EmailServer)


        resp.Redirect(RedirectLocation)


    End Sub


    Public Function LoadFormFields(ByVal nvc As NameValueCollection) As List(Of String)
        Dim fields As New List(Of String)
        If nvc.Count > 0 Then
            For Each s As String In nvc.AllKeys
                If s <> "__VIEWSTATE" Then
                    fields.Add(s + ": " + nvc(s))
                End If
            Next
        End If
        Return fields
    End Function


    Public Function BuildEmail(ByVal ToAddress As String, ByVal FromAddress As String, ByVal Subject As String, ByVal fields As List(Of String)) As MailMessage
        Dim m As New MailMessage(FromAddress, ToAddress)
        m.Subject = Subject
        For Each s As String In fields
            m.Body = m.Body + s + vbCrLf
        Next
        Return m
    End Function


    Public Sub sendEmail(ByVal m As MailMessage, ByVal EmailServer As String)
        Dim serv As New SmtpClient(EmailServer)
        serv.Send(m)
    End Sub


End Class



 

 

Comments

No Comments