
Imports System
Imports Independentsoft.Email
Imports Independentsoft.Email.Smtp
Imports Independentsoft.Email.Mime
Imports DigitalData.Modules.Logging
Imports System.Net.Mail
Imports System.Net
Imports System.Net.Mime

Public Class clsEmail
    Dim Logger As DigitalData.Modules.Logging.Logger
    Private Shared MailAktiv As Boolean = False
    Sub New(MyLogger As LogConfig)
        Logger = MyLogger.GetLogger()
    End Sub
    Public Function Testmail(ByVal mailSubject As String, ByVal mailBody As String, mailto As String,
                                                      mailfrom As String, mailsmtp As String, mailport As Integer, mailUser As String, mailPW As String,
                                                      AUTH_TYPE As String, Optional attment As String = "")
        Try
            Dim oReceipiants As String()
            If mailto.Contains(";") Then
                oReceipiants = mailto.Split(";")
            Else
                ReDim Preserve oReceipiants(0)
                oReceipiants(0) = mailto
            End If
            For Each oMailReceipiant As String In oReceipiants
                Dim sClient = New Mail.SmtpClient(mailsmtp)
                Dim mymesssage As New MailMessage
                sClient.Port = mailport
                If AUTH_TYPE = "SSL" Then
                    sClient.EnableSsl = True
                Else
                    sClient.EnableSsl = False
                End If

                sClient.Credentials = New NetworkCredential(mailUser, mailPW)
                sClient.UseDefaultCredentials = False

                mymesssage.Body = $"This is the body (text will be replaced within profile)! <br> mailsmtp: {mailsmtp} <br> mailport: {mailport} <br> mailUser: {mailUser} <br> mailPW: XXXX <br> AUTH_TYPE: {AUTH_TYPE}"
                Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(mymesssage.Body)
                htmlView.ContentType = New System.Net.Mime.ContentType("text/html")
                mymesssage.AlternateViews.Add(htmlView)

                mymesssage.From = New MailAddress(mailfrom)
                mymesssage.Subject = mailSubject
                mymesssage.To.Add(New MailAddress(oMailReceipiant))

                If attment <> String.Empty Then
                    Dim oAttment As String = attment.Replace("W:\", "\\windream\objects\")

                    If System.IO.File.Exists(oAttment) Then
                        Logger.Info($"working on attachment {oAttment}...")
                        Dim oAttachment As New System.Net.Mail.Attachment(oAttment)

                        mymesssage.Attachments.Add(oAttachment)
                    Else
                        MsgBox($"Attachment {oAttment.ToString} is not existing - Mail won't be send!")
                        Return False
                    End If
                End If


                sClient.Send(mymesssage)
                Logger.Info($"Email has been send to {oMailReceipiant}!!")
            Next


            Return True
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

    End Function
    Public Function Email_Send(ByVal mailSubject As String, ByVal mailBody As String, mailto As String,
                                                      mailfrom As String, mailsmtp As String, mailport As Integer, mailUser As String, mailPW As String,
                                                      AUTH_TYPE As String, Optional attment As String = "", Optional Test As Boolean = False)
        Try
            Dim oError As Boolean = False
            Dim oReceipiants As String()
            If mailto.Contains(";") Then
                oReceipiants = mailto.Split(";")
            Else
                ReDim Preserve oReceipiants(0)
                oReceipiants(0) = mailto
            End If
            For Each oMailReceipiant As String In oReceipiants
                Dim sClient = New Net.Mail.SmtpClient(mailsmtp)
                Dim mymesssage As New MailMessage
                sClient.Port = mailport
                If AUTH_TYPE = "SSL" Then
                    sClient.EnableSsl = True
                Else
                    sClient.EnableSsl = False
                End If

                sClient.Credentials = New NetworkCredential(mailUser, mailPW)
                sClient.UseDefaultCredentials = False
                If Test = True Then
                    mymesssage.Body = $"This is the body (text will be replaced within profile)! <br> mailsmtp: {mailsmtp} <br> mailport: {mailport} <br> mailUser: {mailUser} <br> mailPW: XXXX <br> AUTH_TYPE: {AUTH_TYPE}"
                Else
                    mymesssage.Body = mailBody
                End If

                'mymesssage.IsBodyHtml = True
                Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(mymesssage.Body)
                htmlView.ContentType = New System.Net.Mime.ContentType("text/html")
                mymesssage.AlternateViews.Add(htmlView)
                attment = attment.Replace("W:\", "\\windream\objects\")
                If attment <> String.Empty Then
                    If System.IO.File.Exists(attment) Then
                        Logger.Info($"working on attachment {attment.ToString}...")
                        Dim oAttachment As New System.Net.Mail.Attachment(attment)

                        'If attment.ToLower.EndsWith("pdf") Then
                        '    oAttachment.ContentType = New Independentsoft.Email.Mime.ContentType("application", "pdf")
                        'ElseIf attment.ToLower.EndsWith("jpg") Then
                        '    oAttachment.ContentType = New Independentsoft.Email.Mime.ContentType("application", "jpg")
                        'ElseIf attment.ToLower.EndsWith("docx") Then
                        '    oAttachment.ContentType = New Independentsoft.Email.Mime.ContentType("application", "MS-word")
                        'End If
                        mymesssage.Attachments.Add(oAttachment)
                    Else
                        Logger.Warn($"Attachment {attment.ToString} is not existing - Mail won't be send!")
                        oError = True

                    End If
                End If


                mymesssage.From = New MailAddress(mailfrom)
                mymesssage.Subject = mailSubject
                mymesssage.To.Add(New MailAddress(oMailReceipiant))
                sClient.Send(mymesssage)
            Next
            If oError = False Then
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try

    End Function
    Public Function Email_Send_Independentsoft(ByVal mailSubject As String, ByVal mailBody As String, mailto As String,
                                                      mailfrom As String, mailsmtp As String, mailport As Integer, mailUser As String, mailPW As String,
                                                      AUTH_TYPE As String, Optional attment As String = "")


        Try
            Logger.Debug($"in Email_Send_Independentsoft..")
            Dim empfaenger As String()
            If mailto.Contains(";") Then
                empfaenger = mailto.Split(";")
            Else
                ReDim Preserve empfaenger(0)
                empfaenger(0) = mailto
            End If
            Dim _error As Boolean = False
            'Für jeden Empfänger eine Neue Mail erzeugen
            For Each _mailempfaenger As String In empfaenger
                Logger.Debug($"Working on email for {_mailempfaenger}..")
                Try
                    Dim message As New Message()
                    message.From = New Mailbox(mailfrom, mailfrom)
                    message.[To].Add(New Mailbox(_mailempfaenger))
                    message.Subject = mailSubject
                    Logger.Debug($"Message created..")
                    Dim textBodyPart As New BodyPart()
                    textBodyPart.ContentType = New Independentsoft.Email.Mime.ContentType("text", "html", "utf-8")
                    textBodyPart.ContentTransferEncoding = ContentTransferEncoding.QuotedPrintable
                    textBodyPart.Body = mailBody
                    message.BodyParts.Add(textBodyPart)
                    attment = attment.Replace("W:\", "\\windream\objects\")
                    If attment <> String.Empty Then
                        If System.IO.File.Exists(attment) Then
                            Logger.Info($"working on attachment {attment.ToString}...")
                            Dim attachment1 As New Independentsoft.Email.Mime.Attachment(attment)
                            If attment.ToLower.EndsWith("pdf") Then
                                attachment1.ContentType = New Independentsoft.Email.Mime.ContentType("application", "pdf")
                            ElseIf attment.ToLower.EndsWith("jpg") Then
                                attachment1.ContentType = New Independentsoft.Email.Mime.ContentType("application", "jpg")
                            ElseIf attment.ToLower.EndsWith("docx") Then
                                attachment1.ContentType = New Independentsoft.Email.Mime.ContentType("application", "MS-word")
                            End If
                            message.BodyParts.Add(attachment1)
                        Else
                            Logger.Warn($"Attachment {attment.ToString} is not existing - Mail won't be send!")
                            Return False
                        End If
                    End If
                    Dim client As Smtp.SmtpClient
                    Try
                        client = New Smtp.SmtpClient(mailsmtp, mailport)
                    Catch ex As Exception
                        Logger.Warn("clsEmail.Create Client: " & ex.Message)
                        _error = True
                        Continue For
                    End Try
                    'Try
                    '    client.Connect()
                    'Catch ex As Exception
                    '    Logger.Warn("clsEmail.Client.Connect: " & ex.Message)
                    '    _error = True
                    '    ' Continue For
                    'End Try

                    If AUTH_TYPE = "SSL" Then
                        client.EnableSsl = True
                        '    client.ValidateRemoteCertificate = True
                        Logger.Info("Authentification via SSL.")
                    ElseIf AUTH_TYPE = "TLS" Then
                        ' client.ValidateRemoteCertificate = False
                        client.StartTls()
                        client.EnableSsl = False
                        Logger.Info("Authentification via TLS. SSL disabled")
                    Else
                        client.EnableSsl = False
                        Logger.Info("Authentification NONE. SSL disabled")
                    End If
                    Try
                        client.Connect()
                        Logger.Info("Connected to Client!")
                    Catch ex As Exception
                        Logger.Warn("clsEmail.Client.Connect2: " & ex.Message)
                        _error = True
                        ' Continue For
                    End Try
                    Try
                        If mailsmtp.Contains("office365.com") Then
                            client.Login(mailUser, mailPW, AuthenticationType.None)
                        Else
                            client.Login(mailUser, mailPW)
                        End If

                        Logger.Info("Logged in!")
                    Catch ex As Exception
                        Try
                            If mailsmtp.Contains("office365.com") Then
                                client.Login(mailUser, mailPW, AuthenticationType.Login)
                            Else
                                client.Login(mailUser, mailPW, AuthenticationType.None)
                            End If

                        Catch ex1 As Exception
                            Try
                                client.Login(mailUser, mailPW, AuthenticationType.Login)
                            Catch ex2 As Exception
                                Logger.Warn("clsEmail.Client.Login: " & ex.Message)
                                _error = True
                                client.Disconnect()
                                Continue For
                            End Try
                        End Try
                    End Try
                    Try
                        client.Send(message)
                        Logger.Info("Message to " & _mailempfaenger & " has been send.")
                        _error = False
                    Catch ex As Exception
                        Logger.Warn("clsEmail.Client.Send: " & ex.Message)
                        Try
                            client.Login(mailUser, mailPW, AuthenticationType.Login)
                            client.Send(message)
                        Catch ex1 As Exception
                            Logger.Warn("clsEmail.Client.Send2: " & ex.Message)
                            _error = True
                            client.Disconnect()
                            Continue For
                        End Try



                    End Try
                    client.Disconnect()

                Catch ex As Exception
                    Logger.Error(ex)
                    _error = True
                End Try
            Next

            If _error = True Then
                Return False
            Else
                Return True
            End If
        Catch ex As Exception
            Logger.Error(ex)
            Return False
        End Try
    End Function

End Class
