Authentication with an SMTP server using LAB

Topics: Logging Application Block
Feb 24, 2009 at 4:10 PM
Hi,

I can not find anywhere if it is possible to use an SMTP server which requires an authentication with LAB?

Thanx
Feb 25, 2009 at 3:44 AM
Edited Feb 25, 2009 at 4:10 AM
Are you specifically asking about the EmailTraceListener?  Could you elaborate more on this?


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.
entlib.support@avanade.com
Feb 25, 2009 at 5:51 AM
Yes I am.
My SMTP server requires my client (Outlook) to first log in with POP3 to be able to send something with SMTP. For that I have to check the "Use the same authentication" option in Outlook account advanced options.

Anyway if I just enter the server name and port in LAB Email trace listener it cannot work for my SMTP server requires also a login/passord.
Feb 25, 2009 at 6:22 AM
Ah, I see. This is not supported but you could always modify the source code specifically the Send method of the EmailMessage class.  Configure the Credentials property of the SmtpClient within that method.


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.
entlib.support@avanade.com
Feb 25, 2009 at 6:28 AM
That's what I thought.
Is it the same for an SMTP server using SSL?
Feb 25, 2009 at 6:34 AM
Yes, I think you only need to set the EnableSsl property of the SmtpClient to true.


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.
entlib.support@avanade.com
Feb 25, 2009 at 5:02 PM
I found the same problem, so I took a bit of time to take Microsoft's code and adapt it to include authentication

The logging to the smtp server works fine, but for some reason the elements in the web.config do not get read, so currently I hard coded the values in the tracelistener class
I've included the SMTPTraceListener and SMTPTraceListenerData classes as well as the fragment of the config file that does not get read.
Any insights on why the config file values do not populate the class properties would be greatly appreciated.

Hopefully, this code helps you on your way.

Imports Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners
Imports Microsoft.Practices.EnterpriseLibrary.Logging
Imports System.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Formatters
Imports System.Net.Mail
Imports System
Imports System.Diagnostics


''' <summary>
''' 
''' </summary>
''' <remarks>Currently the SMTPTraceListenerData does not get called. I'm not to sure as to why, but I've run out of time to look at this. So the values are hard coded</remarks>
<ConfigurationElementType(GetType(SMTPTraceListenerData))> _
Public Class SMTPTraceListener
    Inherits FormattedTraceListenerBase

    Private toAddress As String = "test@test.com"
    Private fromAddress As String = "test@test.com"
    Private subjectLineStarter As String = "Exception: "
    Private subjectLineEnder As String = [String].Empty
    Private smtpServer As String = "mail.test.com"
    Private smtpPort As Integer = 25
    Private userName As String = "test@test.com"
    Private password As String = "testing123"

    ''' <summary>
    ''' Initializes a new instance of <see cref="EmailTraceListener"/>.
    ''' </summary>
    Public Sub New()
        MyBase.New()
    End Sub

    ''' <summary>
    ''' Initializes a new instance of <see cref="EmailTraceListener"/> with a <see cref="ILogFormatter"/>.
    ''' </summary>
    ''' <param name="formatter">The formatter.</param>
    Public Sub New(ByVal formatter As ILogFormatter)
        MyBase.New()
        Me.Formatter = formatter
    End Sub

    ''' <summary>
    ''' Initializes a new instance of <see cref="EmailTraceListener"/> with a toaddress, fromaddress,
    ''' subjectlinestarter, subjectlinender, smtpserver, and a formatter
    ''' a <see cref="ILogFormatter"/>.
    ''' </summary>
    ''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
    ''' <param name="fromAddress">Represents from whom the email is sent.</param>
    ''' <param name="subjectLineStarter">Starting text for the subject line.</param>
    ''' <param name="subjectLineEnder">Ending text for the subject line.</param>
    ''' <param name="smtpServer">The name of the SMTP server.</param>
    ''' <param name="formatter">The Formatter <see cref="ILogFormatter"/> which determines how the
    ''' email message should be formatted</param>
    Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal formatter As ILogFormatter)
        Me.New(toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, 25, formatter)
    End Sub

    ''' <summary>
    ''' Initializes a new instance of <see cref="EmailTraceListener"/> with a toaddress, fromaddress,
    ''' subjectlinestarter, subjectlinender, smtpserver, smtpport, and a formatter
    ''' a <see cref="ILogFormatter"/>.
    ''' </summary>
    ''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
    ''' <param name="fromAddress">Represents from whom the email is sent.</param>
    ''' <param name="subjectLineStarter">Starting text for the subject line.</param>
    ''' <param name="subjectLineEnder">Ending text for the subject line.</param>
    ''' <param name="smtpServer">The name of the SMTP server.</param>
    ''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
    ''' <param name="formatter">The Formatter <see cref="ILogFormatter"/> which determines how the
    ''' email message should be formatted</param>
    Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal formatter As ILogFormatter)
        MyBase.New()
        Me.Formatter = formatter
        Me.toAddress = toAddress
        Me.fromAddress = fromAddress
        Me.subjectLineStarter = subjectLineStarter
        Me.subjectLineEnder = subjectLineEnder
        Me.smtpServer = smtpServer
        Me.smtpPort = smtpPort
    End Sub

    Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal smtpUserName As String, ByVal smtpPassword As String, ByVal formatter As ILogFormatter)
        MyBase.New()
        Me.Formatter = formatter
        Me.toAddress = toAddress
        Me.fromAddress = fromAddress
        Me.subjectLineStarter = subjectLineStarter
        Me.subjectLineEnder = subjectLineEnder
        Me.smtpServer = smtpServer
        Me.smtpPort = smtpPort
        Me.userName = smtpUserName
        Me.password = smtpPassword
    End Sub


    ''' <summary>
    ''' Initializes a new instance of <see cref="EmailTraceListener"/> with a toaddress, fromaddress,
    ''' subjectlinestarter, subjectlinender, smtpserver, smtpport, and a formatter
    ''' a <see cref="ILogFormatter"/>.
    ''' </summary>
    ''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
    ''' <param name="fromAddress">Represents from whom the email is sent.</param>
    ''' <param name="subjectLineStarter">Starting text for the subject line.</param>
    ''' <param name="subjectLineEnder">Ending text for the subject line.</param>
    ''' <param name="smtpServer">The name of the SMTP server.</param>
    Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String)
        Me.New(toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, 25)
    End Sub

    ''' <summary>
    ''' Initializes a new instance of <see cref="EmailTraceListener"/> with a toaddress, fromaddress,
    ''' subjectlinestarter, subjectlinender, smtpserver, smtpport, and a formatter
    ''' a <see cref="ILogFormatter"/>.
    ''' </summary>
    ''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
    ''' <param name="fromAddress">Represents from whom the email is sent.</param>
    ''' <param name="subjectLineStarter">Starting text for the subject line.</param>
    ''' <param name="subjectLineEnder">Ending text for the subject line.</param>
    ''' <param name="smtpServer">The name of the SMTP server.</param>
    ''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
    Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer)
        MyBase.New()
        Me.toAddress = toAddress
        Me.fromAddress = fromAddress
        Me.subjectLineStarter = subjectLineStarter
        Me.subjectLineEnder = subjectLineEnder
        Me.smtpServer = smtpServer
        Me.smtpPort = smtpPort
    End Sub



    Public Overloads Overrides Sub Write(ByVal message As String)

        Dim mailMessage As System.Net.Mail.MailMessage = CreateMailMessage(message)
        Dim objMailServer As New System.Net.Mail.SmtpClient(smtpServer, smtpPort)
        Dim smtpUserName As New System.Net.NetworkCredential(Me.userName, Me.password)

        objMailServer.UseDefaultCredentials = False
        objMailServer.Credentials = smtpUserName
        objMailServer.Send(mailMessage)

    End Sub
    ''' <summary>
    ''' Sends an email message given a predefined string
    ''' </summary>
    ''' <param name="logEntry">The logEntry to write as the email message</param>
    Public Overloads Sub Write(ByVal logEntry As LogEntry)

        Dim objMailServer As New System.Net.Mail.SmtpClient(smtpServer, smtpPort)
        Dim smtpUserName As New System.Net.NetworkCredential(Me.userName, Me.password)

        objMailServer.UseDefaultCredentials = False
        objMailServer.Credentials = smtpUserName
        objMailServer.Send(CreateMailMessage(logEntry))

    End Sub
    ''' <summary>
    ''' Sends an email message given a predefined string
    ''' </summary>
    ''' <param name="message">The string to write as the email message</param>
    Public Overloads Overrides Sub WriteLine(ByVal message As String)
        Write(message)
    End Sub


    Protected Function CreateMailMessage(ByVal logEntry As LogEntry) As System.Net.Mail.MailMessage

        Dim header As String = GenerateSubjectPrefix(subjectLineStarter)
        Dim footer As String = GenerateSubjectSuffix(subjectLineEnder)

        Dim sendToSmtpSubject As String = header + logEntry.Severity.ToString() + footer

        Dim message As New MailMessage()
        Dim toAddresses As String() = toAddress.Split(";"c)
        For Each toAddress As String In toAddresses
            message.[To].Add(New MailAddress(toAddress))
        Next

        message.From = New MailAddress(fromAddress)

        message.Body = If((Formatter IsNot Nothing), Formatter.Format(logEntry), logEntry.Message)
        message.Subject = sendToSmtpSubject
        message.BodyEncoding = Text.Encoding.UTF8

        Return message
    End Function

    Protected Function CreateMailMessage(ByVal msg As String) As System.Net.Mail.MailMessage

        Dim header As String = GenerateSubjectPrefix(subjectLineStarter)
        Dim footer As String = GenerateSubjectSuffix(subjectLineEnder)

        Dim sendToSmtpSubject As String = header + msg + footer

        Dim message As New MailMessage()
        Dim toAddresses As String() = toAddress.Split(";"c)
        For Each toAddress As String In toAddresses
            message.[To].Add(New MailAddress(toAddress))
        Next

        message.From = New MailAddress(fromAddress)

        message.Body = msg
        message.Subject = sendToSmtpSubject
        message.BodyEncoding = Text.Encoding.UTF8

        Return message
    End Function

    ''' <summary>
    ''' Determines whether the string is <see langword="null"/> or empty
    ''' </summary>
    ''' <param name="subjectLineMarker">string to evaluate</param>
    ''' <returns>Boolean value that returns true if the string is <see langword="null"/> or empty</returns>
    Private Function IsEmpty(ByVal subjectLineMarker As String) As Boolean
        Return subjectLineMarker Is Nothing OrElse subjectLineMarker.Length = 0
    End Function

    ''' <summary>
    ''' Creates the prefix for the subject line
    ''' </summary>
    ''' <param name="subjectLineField">string to add as the subject line prefix (plus whitespace) if it is not empty.</param>
    ''' <returns>modified string to use as subject line prefix</returns>
    Private Function GenerateSubjectPrefix(ByVal subjectLineField As String) As String
        Return If(IsEmpty(subjectLineField), "", subjectLineField & " ")
    End Function

    ''' <summary>
    ''' Creates the suffix for the subject line.
    ''' </summary>
    ''' <param name="subjectLineField">string to add as the subject line suffix (plus whitespace) if it is not empty.</param>
    ''' <returns>modified string to use as subject line suffix</returns>
    Private Function GenerateSubjectSuffix(ByVal subjectLineField As String) As String
        Return If(IsEmpty(subjectLineField), "", " " & subjectLineField)
    End Function



    ''' <summary>
    ''' Delivers the trace data as an email message.
    ''' </summary>
    ''' <param name="eventCache">The context information provided by <see cref="System.Diagnostics"/>.</param>
    ''' <param name="source">The name of the trace source that delivered the trace data.</param>
    ''' <param name="eventType">The type of event.</param>
    ''' <param name="id">The id of the event.</param>
    ''' <param name="data">The data to trace.</param>
    Public Overloads Overrides Sub TraceData(ByVal eventCache As TraceEventCache, ByVal source As String, ByVal eventType As TraceEventType, ByVal id As Integer, ByVal data As Object)
        If (Me.Filter Is Nothing) OrElse Me.Filter.ShouldTrace(eventCache, source, eventType, id, Nothing, Nothing, _
        data, Nothing) Then
            If TypeOf data Is LogEntry Then
                Write(TryCast(data, LogEntry))
                Flush()
                ' InstrumentationProvider.FireTraceListenerEntryWrittenEvent()
            ElseIf TypeOf data Is String Then
                Write(data)
            Else
                MyBase.TraceData(eventCache, source, eventType, id, data)
            End If
        End If
    End Sub

    ''' <summary>
    ''' Declare the supported attributes for <see cref="EmailTraceListener"/>
    ''' </summary>
    Protected Overloads Overrides Function GetSupportedAttributes() As String()
        Return New String(8) {"formatter", "toAddress", "fromAddress", "subjectLineStarter", "subjectLineEnder", "smtpServer", "smtpPort", "UserName", "Password"}
    End Function


    'Public Shadows ReadOnly Property Attributes() As System.Collections.Specialized.StringDictionary
    '    Get
    '        Dim sd As New System.Collections.Specialized.StringDictionary()
    '        Dim supportedAttributes As String() = GetSupportedAttributes()
    '        For i As Integer = 0 To supportedAttributes.Count - 1
    '            sd.Add(supportedAttributes(i), supportedAttributes(i))
    '        Next
    '        Return sd
    '    End Get

    'End Property

End Class



'===============================================================================
' Microsoft patterns & practices Enterprise Library
' Logging Application Block
'===============================================================================
' Copyright © Microsoft Corporation. All rights reserved.
' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
' OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
' LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
' FITNESS FOR A PARTICULAR PURPOSE.
'===============================================================================

Imports System
Imports System.Configuration
Imports System.Diagnostics
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder
Imports Microsoft.Practices.ObjectBuilder2
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Formatters
Imports Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Configuration


''' <summary>
''' Represents the configuration settings that describe a <see cref="SMTPTraceListener"/>.
''' </summary>
<Assembler(GetType(SMTPTraceListenerAssembler))> _
Public Class SMTPTraceListenerData
    Inherits TraceListenerData



    Private Const toAddressProperty As String = "toAddress"
    Private Const fromAddressProperty As String = "fromAddress"
    Private Const subjectLineStarterProperty As String = "subjectLineStarter"
    Private Const subjectLineEnderProperty As String = "subjectLineEnder"
    Private Const smtpServerProperty As String = "smtpServer"
    Private Const smtpPortProperty As String = "smtpPort"
    Private Const formatterNameProperty As String = "formatter"
    Public Const userNameProperty As String = "UserName"
    Public Const passwordProperty As String = "Password"

    Private strToAddress As String = [String].Empty
    Private strFromAddress As String = [String].Empty
    Private strSubjectLineStarter As String = [String].Empty
    Private strSubjectLineEnder As String = [String].Empty
    Private strSmtpServer As String = [String].Empty
    Private intSmtpPort As Integer = 25
    Private formatterName As String = [String].Empty
    Private strUserName As String = [String].Empty
    Private strPassword As String = [String].Empty


    ''' <summary>
    ''' Initializes a <see cref="SMTPTraceListenerData"/>.
    ''' </summary>
    Public Sub New()
    End Sub

    ''' <summary>
    ''' Initializes a <see cref="SMTPTraceListenerData"/> with a toaddress,
    ''' fromaddress, subjectLineStarter, subjectLineEnder, smtpServer, and a formatter name.
    ''' Default value for the SMTP port is 25
    ''' </summary>
    ''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
    ''' <param name="fromAddress">Represents from whom the email is sent.</param>
    ''' <param name="subjectLineStarter">Starting text for the subject line.</param>
    ''' <param name="subjectLineEnder">Ending text for the subject line.</param>
    ''' <param name="smtpServer">The name of the SMTP server.</param>
    ''' <param name="formatterName">The name of the Formatter <see cref="ILogFormatter"/> which determines how the
    '''email message should be formatted</param>
    Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal formatterName As String)
        Me.New(toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, 25, Nothing, Nothing, formatterName)

    End Sub

    ''' <summary>
    ''' Initializes a <see cref="SMTPTraceListenerData"/> with a toaddress,
    ''' fromaddress, subjectLineStarter, subjectLineEnder, smtpServer, and a formatter name.
    ''' </summary>
    ''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
    ''' <param name="fromAddress">Represents from whom the email is sent.</param>
    ''' <param name="subjectLineStarter">Starting text for the subject line.</param>
    ''' <param name="subjectLineEnder">Ending text for the subject line.</param>
    ''' <param name="smtpServer">The name of the SMTP server.</param>
    ''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
    ''' <param name="formatterName">The name of the Formatter <see cref="ILogFormatter"/> which determines how the
    '''email message should be formatted</param>
    Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal formatterName As String)
        Me.New("unnamed", toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, smtpPort, Nothing, Nothing, formatterName)
    End Sub

    Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal userName As String, ByVal password As String, ByVal formatterName As String)
        Me.New("unnamed", toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, smtpPort, userName, password, formatterName)
    End Sub


    ''' <summary>
    ''' Initializes a <see cref="SMTPTraceListenerData"/> with a toaddress,
    ''' fromaddress, subjectLineStarter, subjectLineEnder, smtpServer, and a formatter name.
    ''' </summary>
    ''' <param name="name">The name of this listener</param>
    ''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
    ''' <param name="fromAddress">Represents from whom the email is sent.</param>
    ''' <param name="subjectLineStarter">Starting text for the subject line.</param>
    ''' <param name="subjectLineEnder">Ending text for the subject line.</param>
    ''' <param name="smtpServer">The name of the SMTP server.</param>
    ''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
    ''' <param name="formatterName">The name of the Formatter <see cref="ILogFormatter"/> which determines how the
    '''email message should be formatted</param>
    Public Sub New(ByVal name As String, ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal userName As String, ByVal password As String, ByVal formatterName As String)
        Me.New(name, toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, smtpPort, userName, password, formatterName, TraceOptions.None)
    End Sub

    ''' <summary>
    ''' Initializes a <see cref="SMTPTraceListenerData"/> with a toaddress,
    ''' fromaddress, subjectLineStarter, subjectLineEnder, smtpServer, a formatter name and trace options.
    ''' </summary>
    ''' <param name="name">The name of this listener</param>
    ''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
    ''' <param name="fromAddress">Represents from whom the email is sent.</param>
    ''' <param name="subjectLineStarter">Starting text for the subject line.</param>
    ''' <param name="subjectLineEnder">Ending text for the subject line.</param>
    ''' <param name="smtpServer">The name of the SMTP server.</param>
    ''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
    ''' <param name="formatterName">The name of the Formatter <see cref="ILogFormatter"/> which determines how the
    '''email message should be formatted</param>
    '''<param name="traceOutputOptions">The trace options.</param>
    Public Sub New(ByVal name As String, ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal userName As String, ByVal password As String, ByVal formatterName As String, ByVal traceOutputOptions As TraceOptions)
        MyBase.New(name, GetType(SMTPTraceListener), traceOutputOptions)
        Me.strToAddress = toAddress
        Me.strFromAddress = fromAddress
        Me.strSubjectLineStarter = subjectLineStarter
        Me.strSubjectLineEnder = subjectLineEnder
        Me.strSmtpServer = smtpServer
        Me.intSmtpPort = smtpPort
        Me.strUserName = userName
        Me.strPassword = password
        Me.Formatter = formatterName
    End Sub

    ''' <summary>
    ''' Gets and sets the ToAddress. One or more email semicolon separated addresses.
    ''' </summary>
    <ConfigurationProperty(toAddressProperty, IsRequired:=True)> _
  Public Property toAddress() As String
        Get
            Return Me.strToAddress
        End Get
        Set(ByVal value As String)
            Me.strToAddress = value
        End Set
    End Property

    <ConfigurationProperty(fromAddressProperty, IsRequired:=True)> _
Public Property fromAddress() As String
        Get
            Return Me.strFromAddress
        End Get
        Set(ByVal value As String)
            Me.strFromAddress = value
        End Set
    End Property

    <ConfigurationProperty(subjectLineStarterProperty, IsRequired:=True)> _
Public Property subjectLineStarter() As String
        Get
            Return Me.strSubjectLineStarter
        End Get
        Set(ByVal value As String)
            Me.strSubjectLineStarter = value
        End Set
    End Property

    <ConfigurationProperty(subjectLineEnderProperty, IsRequired:=True)> _
Public Property subjectLineEnder() As String
        Get
            Return Me.strSubjectLineEnder
        End Get
        Set(ByVal value As String)
            Me.strSubjectLineEnder = value
        End Set
    End Property

    <ConfigurationProperty(smtpServerProperty, IsRequired:=True)> _
  Public Property smtpServer() As String
        Get
            Return Me.strSmtpServer
        End Get
        Set(ByVal value As String)
            Me.strSmtpServer = value
        End Set
    End Property

    <ConfigurationPropertyAttribute(smtpPortProperty, IsRequired:=True)> _
  Public Property smtpPort() As String
        Get
            Return Me.intSmtpPort
        End Get
        Set(ByVal value As String)
            Me.intSmtpPort = value
        End Set
    End Property

    <ConfigurationProperty(userNameProperty, IsRequired:=False)> _
  Public Property UserName() As String
        Get
            Return Me.strUserName
        End Get
        Set(ByVal value As String)
            Me.strUserName = value
        End Set
    End Property

    <ConfigurationProperty(passwordProperty, IsKey:=True, IsRequired:=False)> _
Public Property Password() As String
        Get
            Return Me.strPassword
        End Get
        Set(ByVal value As String)
            Me.strPassword = value
        End Set
    End Property

    ''' <summary>
    ''' Gets and sets the formatter name.
    ''' </summary>
    <ConfigurationProperty(formatterNameProperty, IsRequired:=False)> _
    Public Property Formatter() As String
        Get
            Return Me.formatterName
        End Get
        Set(ByVal value As String)
            Me.formatterName = value
        End Set
    End Property
End Class

''' <summary>
''' This type supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
''' Represents the process to build an <see cref="SMTPTraceListener"/> described by a <see cref="SMTPTraceListenerData"/> configuration object.
''' </summary>
''' <remarks>This type is linked to the <see cref="SMTPTraceListenerData"/> type and it is used by the <see cref="TraceListenerCustomFactory"/>
''' to build the specific <see cref="TraceListener"/> object represented by the configuration object.
''' </remarks>
Public Class SMTPTraceListenerAssembler
    Inherits TraceListenerAsssembler
    ''' <summary>
    ''' This method supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
    ''' Builds an <see cref="SMTPTraceListener"/> based on an instance of <see cref="SMTPTraceListenerData"/>.
    ''' </summary>
    ''' <seealso cref="TraceListenerCustomFactory"/>
    ''' <param name="context">The <see cref="IBuilderContext"/> that represents the current building process.</param>
    ''' <param name="objectConfiguration">The configuration object that describes the object to build. Must be an instance of <see cref="SMTPTraceListenerData"/>.</param>
    ''' <param name="configurationSource">The source for configuration objects.</param>
    ''' <param name="reflectionCache">The cache to use retrieving reflection information.</param>
    ''' <returns>A fully initialized instance of <see cref="SMTPTraceListener"/>.</returns>
    Public Overloads Overrides Function Assemble(ByVal context As IBuilderContext, ByVal objectConfiguration As TraceListenerData, ByVal configurationSource As IConfigurationSource, ByVal reflectionCache As ConfigurationReflectionCache) As TraceListener
        Dim castedObjectConfiguration As SMTPTraceListenerData = DirectCast(objectConfiguration, SMTPTraceListenerData)

        Dim formatter As ILogFormatter = GetFormatter(context, castedObjectConfiguration.Formatter, configurationSource, reflectionCache)

        Dim createdObject As TraceListener = New SMTPTraceListener(castedObjectConfiguration.toAddress, castedObjectConfiguration.fromAddress, castedObjectConfiguration.subjectLineStarter, castedObjectConfiguration.subjectLineEnder, castedObjectConfiguration.smtpServer, castedObjectConfiguration.smtpPort, castedObjectConfiguration.UserName, castedObjectConfiguration.Password, formatter)

        Return createdObject
    End Function
End Class


  <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add toAddress="marc_dentremont@tpsystems.com" fromAddress="noreply@bcfpi.com"
        smtpServer="mail.bcfpi.com" smtpPort="25" userName="noreply@bcfpi.com"
        password="h0R3P71yy9oOd" subjectLineStarter="Exception: " subjectLineEnder="!"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        traceOutputOptions="None" filter="All" type="CustomSmtpTraceListener.SMTPTraceListener, CustomSmtpTraceListener, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
        name="Custom SMTP Trace Listener" initializeData="" formatter="Text Formatter" />
      
    </listeners>
    <formatters>
      <add template="Timestamp: {timestamp}&#xA;Message: {message}&#xA;Category: {category}&#xA;Priority: {priority}&#xA;EventId: {eventid}&#xA;Severity: {severity}&#xA;Title:{title}&#xA;Machine: {machine}&#xA;Application Domain: {appDomain}&#xA;Process Id: {processId}&#xA;Process Name: {processName}&#xA;Win32 Thread Id: {win32ThreadId}&#xA;Thread Name: {threadName}&#xA;Extended Properties: {dictionary({key} - {value}&#xA;)}"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="Text Formatter" />
    </formatters>


Feb 26, 2009 at 6:37 AM
Thanks you Cramhead
Hopefully I'll find time to test that (despite the fact that I do not know VB.NET...) and if something appears to me concerning the .config file reading I'll send you the details.


De : cramhead [mailto:notifications@codeplex.com]
Envoyé : mercredi 25 février 2009 19:03
À : l.forget@kamisen.fr
Objet : Re: Authentication with an SMTP server using LAB [entlib:48388]

From: cramhead

I found the same problem, so I took a bit of time to take Microsoft's code and adapt it to include authentication

The logging to the smtp server works fine, but for some reason the elements in the web.config do not get read, so currently I hard coded the values in the tracelistener class
I've included the SMTPTraceListener and SMTPTraceListenerData classes as well as the fragment of the config file that does not get read.
Any insights on why the config file values do not populate the class properties would be greatly appreciated.

Hopefully, this code helps you on your way.

Imports Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners
Imports Microsoft.Practices.EnterpriseLibrary.Logging
Imports System.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Formatters
Imports System.Net.Mail
Imports System
Imports System.Diagnostics


''' <summary>
'''
''' </summary>
''' <remarks>Currently the SMTPTraceListenerData does not get called. I'm not to sure as to why, but I've run out of time to look at this. So the values are hard coded</remarks>
<ConfigurationElementType(GetType(SMTPTraceListenerData))> _
Public Class SMTPTraceListener
Inherits FormattedTraceListenerBase

Private toAddress As String = "test@test.com"
Private fromAddress As String = "test@test.com"
Private subjectLineStarter As String = "Exception: "
Private subjectLineEnder As String = [String].Empty
Private smtpServer As String = "mail.test.com"
Private smtpPort As Integer = 25
Private userName As String = "test@test.com"
Private password As String = "testing123"

''' <summary>
''' Initializes a new instance of <see cref="EmailTraceListener"/>.
''' </summary>
Public Sub New()
MyBase.New()
End Sub

''' <summary>
''' Initializes a new instance of <see cref="EmailTraceListener"/> with a <see cref="ILogFormatter"/>.
''' </summary>
''' <param name="formatter">The formatter.</param>
Public Sub New(ByVal formatter As ILogFormatter)
MyBase.New()
Me.Formatter = formatter
End Sub

''' <summary>
''' Initializes a new instance of <see cref="EmailTraceListener"/> with a toaddress, fromaddress,
''' subjectlinestarter, subjectlinender, smtpserver, and a formatter
''' a <see cref="ILogFormatter"/>.
''' </summary>
''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
''' <param name="fromAddress">Represents from whom the email is sent.</param>
''' <param name="subjectLineStarter">Starting text for the subject line.</param>
''' <param name="subjectLineEnder">Ending text for the subject line.</param>
''' <param name="smtpServer">The name of the SMTP server.</param>
''' <param name="formatter">The Formatter <see cref="ILogFormatter"/> which determines how the
''' email message should be formatted</param>
Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal formatter As ILogFormatter)
Me.New(toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, 25, formatter)
End Sub

''' <summary>
''' Initializes a new instance of <see cref="EmailTraceListener"/> with a toaddress, fromaddress,
''' subjectlinestarter, subjectlinender, smtpserver, smtpport, and a formatter
''' a <see cref="ILogFormatter"/>.
''' </summary>
''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
''' <param name="fromAddress">Represents from whom the email is sent.</param>
''' <param name="subjectLineStarter">Starting text for the subject line.</param>
''' <param name="subjectLineEnder">Ending text for the subject line.</param>
''' <param name="smtpServer">The name of the SMTP server.</param>
''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
''' <param name="formatter">The Formatter <see cref="ILogFormatter"/> which determines how the
''' email message should be formatted</param>
Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal formatter As ILogFormatter)
MyBase.New()
Me.Formatter = formatter
Me.toAddress = toAddress
Me.fromAddress = fromAddress
Me.subjectLineStarter = subjectLineStarter
Me.subjectLineEnder = subjectLineEnder
Me.smtpServer = smtpServer
Me.smtpPort = smtpPort
End Sub

Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal smtpUserName As String, ByVal smtpPassword As String, ByVal formatter As ILogFormatter)
MyBase.New()
Me.Formatter = formatter
Me.toAddress = toAddress
Me.fromAddress = fromAddress
Me.subjectLineStarter = subjectLineStarter
Me.subjectLineEnder = subjectLineEnder
Me.smtpServer = smtpServer
Me.smtpPort = smtpPort
Me.userName = smtpUserName
Me.password = smtpPassword
End Sub


''' <summary>
''' Initializes a new instance of <see cref="EmailTraceListener"/> with a toaddress, fromaddress,
''' subjectlinestarter, subjectlinender, smtpserver, smtpport, and a formatter
''' a <see cref="ILogFormatter"/>.
''' </summary>
''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
''' <param name="fromAddress">Represents from whom the email is sent.</param>
''' <param name="subjectLineStarter">Starting text for the subject line.</param>
''' <param name="subjectLineEnder">Ending text for the subject line.</param>
''' <param name="smtpServer">The name of the SMTP server.</param>
Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String)
Me.New(toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, 25)
End Sub

''' <summary>
''' Initializes a new instance of <see cref="EmailTraceListener"/> with a toaddress, fromaddress,
''' subjectlinestarter, subjectlinender, smtpserver, smtpport, and a formatter
''' a <see cref="ILogFormatter"/>.
''' </summary>
''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
''' <param name="fromAddress">Represents from whom the email is sent.</param>
''' <param name="subjectLineStarter">Starting text for the subject line.</param>
''' <param name="subjectLineEnder">Ending text for the subject line.</param>
''' <param name="smtpServer">The name of the SMTP server.</param>
''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer)
MyBase.New()
Me.toAddress = toAddress
Me.fromAddress = fromAddress
Me.subjectLineStarter = subjectLineStarter
Me.subjectLineEnder = subjectLineEnder
Me.smtpServer = smtpServer
Me.smtpPort = smtpPort
End Sub



Public Overloads Overrides Sub Write(ByVal message As String)

Dim mailMessage As System.Net.Mail.MailMessage = CreateMailMessage(message)
Dim objMailServer As New System.Net.Mail.SmtpClient(smtpServer, smtpPort)
Dim smtpUserName As New System.Net.NetworkCredential(Me.userName, Me.password)

objMailServer.UseDefaultCredentials = False
objMailServer.Credentials = smtpUserName
objMailServer.Send(mailMessage)

End Sub
''' <summary>
''' Sends an email message given a predefined string
''' </summary>
''' <param name="logEntry">The logEntry to write as the email message</param>
Public Overloads Sub Write(ByVal logEntry As LogEntry)

Dim objMailServer As New System.Net.Mail.SmtpClient(smtpServer, smtpPort)
Dim smtpUserName As New System.Net.NetworkCredential(Me.userName, Me.password)

objMailServer.UseDefaultCredentials = False
objMailServer.Credentials = smtpUserName
objMailServer.Send(CreateMailMessage(logEntry))

End Sub
''' <summary>
''' Sends an email message given a predefined string
''' </summary>
''' <param name="message">The string to write as the email message</param>
Public Overloads Overrides Sub WriteLine(ByVal message As String)
Write(message)
End Sub


Protected Function CreateMailMessage(ByVal logEntry As LogEntry) As System.Net.Mail.MailMessage

Dim header As String = GenerateSubjectPrefix(subjectLineStarter)
Dim footer As String = GenerateSubjectSuffix(subjectLineEnder)

Dim sendToSmtpSubject As String = header + logEntry.Severity.ToString() + footer

Dim message As New MailMessage()
Dim toAddresses As String() = toAddress.Split(";"c)
For Each toAddress As String In toAddresses
message.[To].Add(New MailAddress(toAddress))
Next

message.From = New MailAddress(fromAddress)

message.Body = If((Formatter IsNot Nothing), Formatter.Format(logEntry), logEntry.Message)
message.Subject = sendToSmtpSubject
message.BodyEncoding = Text.Encoding.UTF8

Return message
End Function

Protected Function CreateMailMessage(ByVal msg As String) As System.Net.Mail.MailMessage

Dim header As String = GenerateSubjectPrefix(subjectLineStarter)
Dim footer As String = GenerateSubjectSuffix(subjectLineEnder)

Dim sendToSmtpSubject As String = header + msg + footer

Dim message As New MailMessage()
Dim toAddresses As String() = toAddress.Split(";"c)
For Each toAddress As String In toAddresses
message.[To].Add(New MailAddress(toAddress))
Next

message.From = New MailAddress(fromAddress)

message.Body = msg
message.Subject = sendToSmtpSubject
message.BodyEncoding = Text.Encoding.UTF8

Return message
End Function

''' <summary>
''' Determines whether the string is <see langword="null"/> or empty
''' </summary>
''' <param name="subjectLineMarker">string to evaluate</param>
''' <returns>Boolean value that returns true if the string is <see langword="null"/> or empty</returns>
Private Function IsEmpty(ByVal subjectLineMarker As String) As Boolean
Return subjectLineMarker Is Nothing OrElse subjectLineMarker.Length = 0
End Function

''' <summary>
''' Creates the prefix for the subject line
''' </summary>
''' <param name="subjectLineField">string to add as the subject line prefix (plus whitespace) if it is not empty.</param>
''' <returns>modified string to use as subject line prefix</returns>
Private Function GenerateSubjectPrefix(ByVal subjectLineField As String) As String
Return If(IsEmpty(subjectLineField), "", subjectLineField & " ")
End Function

''' <summary>
''' Creates the suffix for the subject line.
''' </summary>
''' <param name="subjectLineField">string to add as the subject line suffix (plus whitespace) if it is not empty.</param>
''' <returns>modified string to use as subject line suffix</returns>
Private Function GenerateSubjectSuffix(ByVal subjectLineField As String) As String
Return If(IsEmpty(subjectLineField), "", " " & subjectLineField)
End Function



''' <summary>
''' Delivers the trace data as an email message.
''' </summary>
''' <param name="eventCache">The context information provided by <see cref="System.Diagnostics"/>.</param>
''' <param name="source">The name of the trace source that delivered the trace data.</param>
''' <param name="eventType">The type of event.</param>
''' <param name="id">The id of the event.</param>
''' <param name="data">The data to trace.</param>
Public Overloads Overrides Sub TraceData(ByVal eventCache As TraceEventCache, ByVal source As String, ByVal eventType As TraceEventType, ByVal id As Integer, ByVal data As Object)
If (Me.Filter Is Nothing) OrElse Me.Filter.ShouldTrace(eventCache, source, eventType, id, Nothing, Nothing, _
data, Nothing) Then
If TypeOf data Is LogEntry Then
Write(TryCast(data, LogEntry))
Flush()
' InstrumentationProvider.FireTraceListenerEntryWrittenEvent()
ElseIf TypeOf data Is String Then
Write(data)
Else
MyBase.TraceData(eventCache, source, eventType, id, data)
End If
End If
End Sub

''' <summary>
''' Declare the supported attributes for <see cref="EmailTraceListener"/>
''' </summary>
Protected Overloads Overrides Function GetSupportedAttributes() As String()
Return New String(8) {"formatter", "toAddress", "fromAddress", "subjectLineStarter", "subjectLineEnder", "smtpServer", "smtpPort", "UserName", "Password"}
End Function


'Public Shadows ReadOnly Property Attributes() As System.Collections.Specialized.StringDictionary
' Get
' Dim sd As New System.Collections.Specialized.StringDictionary()
' Dim supportedAttributes As String() = GetSupportedAttributes()
' For i As Integer = 0 To supportedAttributes.Count - 1
' sd.Add(supportedAttributes(i), supportedAttributes(i))
' Next
' Return sd
' End Get

'End Property

End Class



'===============================================================================
' Microsoft patterns & practices Enterprise Library
' Logging Application Block
'===============================================================================
' Copyright © Microsoft Corporation. All rights reserved.
' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
' OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
' LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
' FITNESS FOR A PARTICULAR PURPOSE.
'===============================================================================

Imports System
Imports System.Configuration
Imports System.Diagnostics
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder
Imports Microsoft.Practices.ObjectBuilder2
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Formatters
Imports Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Configuration


''' <summary>
''' Represents the configuration settings that describe a <see cref="SMTPTraceListener"/>.
''' </summary>
<Assembler(GetType(SMTPTraceListenerAssembler))> _
Public Class SMTPTraceListenerData
Inherits TraceListenerData



Private Const toAddressProperty As String = "toAddress"
Private Const fromAddressProperty As String = "fromAddress"
Private Const subjectLineStarterProperty As String = "subjectLineStarter"
Private Const subjectLineEnderProperty As String = "subjectLineEnder"
Private Const smtpServerProperty As String = "smtpServer"
Private Const smtpPortProperty As String = "smtpPort"
Private Const formatterNameProperty As String = "formatter"
Public Const userNameProperty As String = "UserName"
Public Const passwordProperty As String = "Password"

Private strToAddress As String = [String].Empty
Private strFromAddress As String = [String].Empty
Private strSubjectLineStarter As String = [String].Empty
Private strSubjectLineEnder As String = [String].Empty
Private strSmtpServer As String = [String].Empty
Private intSmtpPort As Integer = 25
Private formatterName As String = [String].Empty
Private strUserName As String = [String].Empty
Private strPassword As String = [String].Empty


''' <summary>
''' Initializes a <see cref="SMTPTraceListenerData"/>.
''' </summary>
Public Sub New()
End Sub

''' <summary>
''' Initializes a <see cref="SMTPTraceListenerData"/> with a toaddress,
''' fromaddress, subjectLineStarter, subjectLineEnder, smtpServer, and a formatter name.
''' Default value for the SMTP port is 25
''' </summary>
''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
''' <param name="fromAddress">Represents from whom the email is sent.</param>
''' <param name="subjectLineStarter">Starting text for the subject line.</param>
''' <param name="subjectLineEnder">Ending text for the subject line.</param>
''' <param name="smtpServer">The name of the SMTP server.</param>
''' <param name="formatterName">The name of the Formatter <see cref="ILogFormatter"/> which determines how the
'''email message should be formatted</param>
Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal formatterName As String)
Me.New(toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, 25, Nothing, Nothing, formatterName)

End Sub

''' <summary>
''' Initializes a <see cref="SMTPTraceListenerData"/> with a toaddress,
''' fromaddress, subjectLineStarter, subjectLineEnder, smtpServer, and a formatter name.
''' </summary>
''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
''' <param name="fromAddress">Represents from whom the email is sent.</param>
''' <param name="subjectLineStarter">Starting text for the subject line.</param>
''' <param name="subjectLineEnder">Ending text for the subject line.</param>
''' <param name="smtpServer">The name of the SMTP server.</param>
''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
''' <param name="formatterName">The name of the Formatter <see cref="ILogFormatter"/> which determines how the
'''email message should be formatted</param>
Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal formatterName As String)
Me.New("unnamed", toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, smtpPort, Nothing, Nothing, formatterName)
End Sub

Public Sub New(ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal userName As String, ByVal password As String, ByVal formatterName As String)
Me.New("unnamed", toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, smtpPort, userName, password, formatterName)
End Sub


''' <summary>
''' Initializes a <see cref="SMTPTraceListenerData"/> with a toaddress,
''' fromaddress, subjectLineStarter, subjectLineEnder, smtpServer, and a formatter name.
''' </summary>
''' <param name="name">The name of this listener</param>
''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
''' <param name="fromAddress">Represents from whom the email is sent.</param>
''' <param name="subjectLineStarter">Starting text for the subject line.</param>
''' <param name="subjectLineEnder">Ending text for the subject line.</param>
''' <param name="smtpServer">The name of the SMTP server.</param>
''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
''' <param name="formatterName">The name of the Formatter <see cref="ILogFormatter"/> which determines how the
'''email message should be formatted</param>
Public Sub New(ByVal name As String, ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal userName As String, ByVal password As String, ByVal formatterName As String)
Me.New(name, toAddress, fromAddress, subjectLineStarter, subjectLineEnder, smtpServer, smtpPort, userName, password, formatterName, TraceOptions.None)
End Sub

''' <summary>
''' Initializes a <see cref="SMTPTraceListenerData"/> with a toaddress,
''' fromaddress, subjectLineStarter, subjectLineEnder, smtpServer, a formatter name and trace options.
''' </summary>
''' <param name="name">The name of this listener</param>
''' <param name="toAddress">A semicolon delimited string the represents to whom the email should be sent.</param>
''' <param name="fromAddress">Represents from whom the email is sent.</param>
''' <param name="subjectLineStarter">Starting text for the subject line.</param>
''' <param name="subjectLineEnder">Ending text for the subject line.</param>
''' <param name="smtpServer">The name of the SMTP server.</param>
''' <param name="smtpPort">The port on the SMTP server to use for sending the email.</param>
''' <param name="formatterName">The name of the Formatter <see cref="ILogFormatter"/> which determines how the
'''email message should be formatted</param>
'''<param name="traceOutputOptions">The trace options.</param>
Public Sub New(ByVal name As String, ByVal toAddress As String, ByVal fromAddress As String, ByVal subjectLineStarter As String, ByVal subjectLineEnder As String, ByVal smtpServer As String, ByVal smtpPort As Integer, ByVal userName As String, ByVal password As String, ByVal formatterName As String, ByVal traceOutputOptions As TraceOptions)
MyBase.New(name, GetType(SMTPTraceListener), traceOutputOptions)
Me.strToAddress = toAddress
Me.strFromAddress = fromAddress
Me.strSubjectLineStarter = subjectLineStarter
Me.strSubjectLineEnder = subjectLineEnder
Me.strSmtpServer = smtpServer
Me.intSmtpPort = smtpPort
Me.strUserName = userName
Me.strPassword = password
Me.Formatter = formatterName
End Sub

''' <summary>
''' Gets and sets the ToAddress. One or more email semicolon separated addresses.
''' </summary>
<ConfigurationProperty(toAddressProperty, IsRequired:=True)> _
Public Property toAddress() As String
Get
Return Me.strToAddress
End Get
Set(ByVal value As String)
Me.strToAddress = value
End Set
End Property

<ConfigurationProperty(fromAddressProperty, IsRequired:=True)> _
Public Property fromAddress() As String
Get
Return Me.strFromAddress
End Get
Set(ByVal value As String)
Me.strFromAddress = value
End Set
End Property

<ConfigurationProperty(subjectLineStarterProperty, IsRequired:=True)> _
Public Property subjectLineStarter() As String
Get
Return Me.strSubjectLineStarter
End Get
Set(ByVal value As String)
Me.strSubjectLineStarter = value
End Set
End Property

<ConfigurationProperty(subjectLineEnderProperty, IsRequired:=True)> _
Public Property subjectLineEnder() As String
Get
Return Me.strSubjectLineEnder
End Get
Set(ByVal value As String)
Me.strSubjectLineEnder = value
End Set
End Property

<ConfigurationProperty(smtpServerProperty, IsRequired:=True)> _
Public Property smtpServer() As String
Get
Return Me.strSmtpServer
End Get
Set(ByVal value As String)
Me.strSmtpServer = value
End Set
End Property

<ConfigurationPropertyAttribute(smtpPortProperty, IsRequired:=True)> _
Public Property smtpPort() As String
Get
Return Me.intSmtpPort
End Get
Set(ByVal value As String)
Me.intSmtpPort = value
End Set
End Property

<ConfigurationProperty(userNameProperty, IsRequired:=False)> _
Public Property UserName() As String
Get
Return Me.strUserName
End Get
Set(ByVal value As String)
Me.strUserName = value
End Set
End Property

<ConfigurationProperty(passwordProperty, IsKey:=True, IsRequired:=False)> _
Public Property Password() As String
Get
Return Me.strPassword
End Get
Set(ByVal value As String)
Me.strPassword = value
End Set
End Property

''' <summary>
''' Gets and sets the formatter name.
''' </summary>
<ConfigurationProperty(formatterNameProperty, IsRequired:=False)> _
Public Property Formatter() As String
Get
Return Me.formatterName
End Get
Set(ByVal value As String)
Me.formatterName = value
End Set
End Property
End Class

''' <summary>
''' This type supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
''' Represents the process to build an <see cref="SMTPTraceListener"/> described by a <see cref="SMTPTraceListenerData"/> configuration object.
''' </summary>
''' <remarks>This type is linked to the <see cref="SMTPTraceListenerData"/> type and it is used by the <see cref="TraceListenerCustomFactory"/>
''' to build the specific <see cref="TraceListener"/> object represented by the configuration object.
''' </remarks>
Public Class SMTPTraceListenerAssembler
Inherits TraceListenerAsssembler
''' <summary>
''' This method supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
''' Builds an <see cref="SMTPTraceListener"/> based on an instance of <see cref="SMTPTraceListenerData"/>.
''' </summary>
''' <seealso cref="TraceListenerCustomFactory"/>
''' <param name="context">The <see cref="IBuilderContext"/> that represents the current building process.</param>
''' <param name="objectConfiguration">The configuration object that describes the object to build. Must be an instance of <see cref="SMTPTraceListenerData"/>.</param>
''' <param name="configurationSource">The source for configuration objects.</param>
''' <param name="reflectionCache">The cache to use retrieving reflection information.</param>
''' <returns>A fully initialized instance of <see cref="SMTPTraceListener"/>.</returns>
Public Overloads Overrides Function Assemble(ByVal context As IBuilderContext, ByVal objectConfiguration As TraceListenerData, ByVal configurationSource As IConfigurationSource, ByVal reflectionCache As ConfigurationReflectionCache) As TraceListener
Dim castedObjectConfiguration As SMTPTraceListenerData = DirectCast(objectConfiguration, SMTPTraceListenerData)

Dim formatter As ILogFormatter = GetFormatter(context, castedObjectConfiguration.Formatter, configurationSource, reflectionCache)

Dim createdObject As TraceListener = New SMTPTraceListener(castedObjectConfiguration.toAddress, castedObjectConfiguration.fromAddress, castedObjectConfiguration.subjectLineStarter, castedObjectConfiguration.subjectLineEnder, castedObjectConfiguration.smtpServer, castedObjectConfiguration.smtpPort, castedObjectConfiguration.UserName, castedObjectConfiguration.Password, formatter)

Return createdObject
End Function
End Class


<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add toAddress="marc_dentremont@tpsystems.com" fromAddress="noreply@bcfpi.com"
smtpServer="mail.bcfpi.com" smtpPort="25" userName="noreply@bcfpi.com"
password="h0R3P71yy9oOd" subjectLineStarter="Exception: " subjectLineEnder="!"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None" filter="All" type="CustomSmtpTraceListener.SMTPTraceListener, CustomSmtpTraceListener, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
name="Custom SMTP Trace Listener" initializeData="" formatter="Text Formatter" />
</listeners>
<formatters>
<add template="Timestamp: {timestamp} Message: {message} Category: {category} Priority: {priority} EventId: {eventid} Severity: {severity} Title:{title} Machine: {machine} Application Domain: {appDomain} Process Id: {processId} Process Name: {processName} Win32 Thread Id: {win32ThreadId} Thread Name: {threadName} Extended Properties: {dictionary({key} - {value} )}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Text Formatter" />
</formatters>


Feb 27, 2009 at 5:09 PM
I converted the c# code to VB.net as our project is in VB.NET. There are converter to go either direction. The one I often use is http://www.developerfusion.com/tools/convert/vb-to-csharp/

Hope it helps.

Mar 2, 2009 at 5:47 PM
Yes, great!
I did not know of such tools ;)


De : cramhead [mailto:notifications@codeplex.com]
Envoyé : vendredi 27 février 2009 19:10
À : l.forget@kamisen.fr
Objet : Re: Authentication with an SMTP server using LAB [entlib:48388]

From: cramhead

I converted the c# code to VB.net as our project is in VB.NET. There are converter to go either direction. The one I often use is http://www.developerfusion.com/tools/convert/vb-to-csharp/

Hope it helps.