MailServer Class

This page is part of the Class Library Pages collection.
Click the icon to see the index.

Implementation

VB.NET

{copytext|VbSample}
Dim senderEmail As String
Dim hostName As String
Dim recipient As String
Dim subject As String
Dim body As String

'TODO: Set values of variables

Dim ms As MailServer = New MailServer(senderEmail, hostName)
ms.SendEmail(recipient, subject, body, MailFormat.PlainText)

C#

{copytext|CsSample}
TODO


Source Code

The following class provides a means of sending email via a specified SMTP server.

VB.NET

{copytext|VbSource}
Imports System.Net
Imports System.Net.Mail

Public Enum MailFormat
    Html
    PlainText
End Enum
Public Class MailServer

    Private _hostName As String
    Private _useDefaultCredentials As Boolean
    Private _senderEmail As String
    Private _password As String
    Private _method As SmtpDeliveryMethod

    Public Sub New(ByVal senderEmail As String)

        _hostName = "127.0.0.1"
        _senderEmail = senderEmail
        _useDefaultCredentials = True
        _method = SmtpDeliveryMethod.PickupDirectoryFromIis

    End Sub

    Public Sub New(ByVal senderEmail As String, ByVal hostName As String)

        _hostName = hostName
        _senderEmail = senderEmail
        _useDefaultCredentials = True
        _method = SmtpDeliveryMethod.Network

    End Sub

    Public Sub New(ByVal senderEmail As String, ByVal hostName As String, ByVal password As String)

        _hostName = hostName
        _senderEmail = senderEmail
        _password = password
        _useDefaultCredentials = False
        _method = SmtpDeliveryMethod.Network

    End Sub

    Public Sub SendEmail(ByVal recipient As String, ByVal subject As String, ByVal body As _
    String, ByVal format As MailFormat)

        Dim portNumber As Integer = 25
        Dim smtpClient As SmtpClient = New SmtpClient(_hostName, portNumber)
        smtpClient.UseDefaultCredentials = _useDefaultCredentials
        smtpClient.DeliveryMethod = _method

        If Not _useDefaultCredentials Then
            smtpClient.Credentials = New System.Net.NetworkCredential(_senderEmail, _password)
        End If

        Dim msg As MailMessage = New MailMessage(_senderEmail, recipient, subject, body)
        msg.IsBodyHtml = (format = MailFormat.Html)
        smtpClient.Send(msg)

    End Sub

End Class

C#

{copytext|CsSource}
TODO