Sean's Personal .NET Code Samples And References

ASP.NET sending email System.Net.Mail in Visual Basic

Here is the code for system.net in the web.config file.

The from is default, so you don't have to add it when sending the mail.
Port 25 is the standard email port, yours could be different.

<!--EMAIL SETTINGS-->
<system.net>
    <mailSettings>
      <smtp from="Default From Address" deliveryMethod="Network">
        <network 
             host="Your Email Server"
             port="25"
             userName="Your Username"
             password="Your Password" />
      </smtp>
    </mailSettings>
</system.net>

Here is the form for the .aspx page.

<table>
    <tr>
        <td>Your Email:</td>
        <td><asp:TextBox runat="server" ID="txtFromAddress" /></td>
    </tr>
    <tr>
        <td>Your Name:</td>
        <td><asp:TextBox runat="server" ID="txtFrom" /></td>
    </tr>
    <tr>
        <td>Subject:</td>
        <td><asp:TextBox runat="server" ID="txtSubject" /></td>
    </tr>
    <tr>
        <td valign="top">Comments:</td>
        <td><asp:TextBox runat="server" ID="txtComment" TextMode="MultiLine" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button runat="server" ID="btnSubmit" Text="Submit" 
                UseSubmitBehavior="true" CausesValidation="true" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Literal runat="server" ID="litConfrimation" />
        </td>
    </tr>
</table>

Here are the form validators

Make sure the user entered a comment.
<asp:RequiredFieldValidator ID="rfvComment" runat="server" 
    ErrorMessage="Comment is a required field." 
    Display="None" ControlToValidate="txtComment" SetFocusOnError="true" />

Make sure it the user entered an email address is in the correct format.    
<asp:RegularExpressionValidator ID="revEmailFormat" runat="server" 
    ErrorMessage="Invalid email format." 
    Display="None" ControlToValidate="txtFromAddress" SetFocusOnError="true" 
    ValidationExpression="^[\w\.-]+@[\w-]+\.[\w\.-]+$" />

Alert the user with a summary.
<asp:ValidationSummary ID="ValidationSummary" runat="server" 
    DisplayMode="BulletList" HeaderText="Cannot submit the form!" 
    ShowMessageBox="true" ShowSummary="true" />  

Here is the server side code for sending the email.

'IMPORT THE .NET.MAIL
Imports System.Net.Mail

'CHECK THAT THE PAGE IS VALID TO PREVENT ERRORS
    (THIS GOES IN THE BUTTON CLICK EVENT)
If Page.IsValid Then

    'DECLARE AND SET A DEFAULT SUBJECT
    Dim Subject As String = "SeanMarcellus.com Contact Form"
    'IF THE USER INPUT A SUBJECT WE'LL USE IT INSTEAD
    If txtSubject.Text.Length > 0 Then Subject = txtSubject.Text.ToString

    'DECLARE THE BODY VARIABLE AND ADD THE FIRST LINE
    Dim Body As String = "<h4>This email was sent from the seanmarcellus.com contact form.</h4>"

    'IF THE USER ENTERED THEIR NAME WE'LL ADD THAT TO THE EMAIL ALSO
    If txtFrom.Text.Length > 0 Then Body += "<b>Sender:</b> " & txtFrom.Text.ToString & "<br /><br />"

    'DECLARE THE COMMENT AND SET THE VALUE
    Dim comment As String = txtComment.Text.ToString

    'I LIKE TO REPLACE SOME OF THE HTML SO I CAN VIEW EXACTLY WHAT THE USER ENTERED
    comment = Replace(comment, "<", "&#60;")
    comment = Replace(comment, "'", "&#39;")
    comment = Replace(comment, Chr(34), "&#34;") 'DOUBLE QUOTES
    
    'WITH THIS I CAN SEE THE HYPERLINK
        (I DON'T LIKE CLICKING LINKS IN MY EMAIL WHEN I'M  NOT SURE WHERE THE CAME FROM)
    comment = Replace(comment, "http://", "URL: ")

    'WHEN USING HTML EMAIL I LIKE TO REPLACE ALL THE LINEBREAKS WITH BR TAGS 
    comment = Replace(comment, vbCrLf, "<br />")

    'ADDING A HEADING TO THE USERS COMMENT 
    Body += "<b>Comment:</b> " & comment

    'DECLARE THE MAIL MESSAGE
    Dim message As New MailMessage

    'ADD THE TO EMAIL ADDRESS
    message.To.Add(New MailAddress("Your email address.com"))

    'IF THE USER ENTERED THEIR EMAIL
        SET THE FROM TO THEM SO REPLY WILL WORK WHEN THE MESSAGE IS RECIEVED
        (OTHERWISE IT WILL DEFAULT TO THE FROM IN THE web.config FILE.)
    If txtFromAddress.Text.Length > 0 Then message.From = New MailAddress(txtFromAddress.Text.ToString)

    'ADD THE VARIBLES TO THE MAIL MESSAGE
    message.Subject = Subject
    message.Body = Body
    message.IsBodyHtml = True

    'DECLARE THE MAIL CLIENT TO SEND THE MESSAGE
    Dim mailClient As SmtpClient = New SmtpClient

    Try 'TO CATCH ANY ERROR THAT MAY OCCURE
        'SEND THE EMAIL
        mailClient.Send(message)
        'ADD SOME CLEAN UP
        message.Dispose()
        
        'CLEAR THE FORM SO IT IS OBVIOUSE SOMETHING HAPPEND
        txtComment.Text = ""
        txtFrom.Text = ""
        txtFromAddress.Text = ""
        txtSubject.Text = ""

        'SHOW THE USER A CONFIRMATION
        litConfrimation.Text = "<h4>Thank you,<br />Your email has been sent to Sean Marcellus.</h4>"
        
    Catch ex As Exception 'IF THERE WAS AN ERROR LET THE USER KNOW IT DIDN'T WORK
        litConfrimation.Text = "<h4 class='ErrorAC'>" & ex.Message.ToString & "</h4>"
        'CLEAR THE ERROR
        Err.Clear()
    End Try
End If
Sean Marcellus
There are 10 kinds of people e in this world, those who understand binary and those who don’t.