Imports System.Net.Mail
Imports System.IO
Imports System.Data.SqlClient

Module Mail
    Dim sPath As String = System.AppDomain.CurrentDomain.BaseDirectory
    Dim last_sent As String = sPath & "\last_sent.txt" '" & Now.ToString("ddMMyyyyHHmmss") & ".csv"

    Sub Main()
        If Not IO.File.Exists(last_sent) Then
            IO.File.Create(last_sent)
        End If
      
        System.Console.WriteLine("Starte Wölfl-Mail...")
        If SendEmail() Then
            Try
                Dim outFile As IO.StreamWriter = Nothing
                outFile = My.Computer.FileSystem.OpenTextFileWriter(last_sent, False)
                outFile.Write(Now.AddDays(-1).ToShortDateString)
                outFile.Close()
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
    End Sub

    Function getDateFromFile() As String
        Try
            Dim instr = New StreamReader(last_sent)
            Dim d As Date = CDate(instr.ReadLine).AddDays(1)
            instr.Close()
            Return d
        Catch ex As Exception
            Return ""
        End Try
    End Function

    Private Function SendEmail() As Boolean
        Dim Msg As New MailMessage
        Dim myCredentials As New System.Net.NetworkCredential
        myCredentials.UserName = "al@verag.ag"
        myCredentials.Password = "Luxandreas#2"
        Msg.IsBodyHtml = False
        Dim mySmtpsvr As New SmtpClient()
        mySmtpsvr.Host = "smtp.1und1.de" 'bei web.de
        mySmtpsvr.Port = 587 '25
        mySmtpsvr.UseDefaultCredentials = False
        mySmtpsvr.Credentials = myCredentials
        System.Console.WriteLine("E-Mail Daten initialisiert...")
        Try
            Dim datum As String = Now.AddDays(-1).ToShortDateString
            Dim von = getDateFromFile()
            If von = "" Then von = datum
            Dim bis = datum
            System.Console.WriteLine("Erstelle CSV...")
            Dim csv As String = genCSV(von, bis)
            System.Console.WriteLine("CSV erstellt...")
            If csv <> "" And Not csv.StartsWith("ERROR: ") Then
                System.Console.WriteLine("Sende E-Mail...")
                Msg.From = New MailAddress("al@verag.ag")
                Msg.To.Add("al@verag.ag")
                Msg.Subject = "VERAG: Gutschriften/Rechnungen " & von & "-" & bis
                Msg.Body = "Sehr geehrte Damen und Herren," & vbNewLine & vbNewLine & "anbei erhalten Sie die Gutschriften/Rechnungen im Zeitraum: " & von & "-" & bis & ". " & vbNewLine & vbNewLine & "Mit frendlichen Grüßen " & vbNewLine & "Ihr VERAG MDM-TEAM" & vbNewLine & vbNewLine & vbNewLine & "Automatisch generiertes E-Mail."

                Dim attachment As Attachment = New Attachment(File.OpenRead(csv), "WOELFL_" & von & "-" & bis & ".csv")
                Msg.Attachments.Add(attachment)

                mySmtpsvr.Send(Msg)

                System.Console.WriteLine("E-Mail gesendet.")
                '       MsgBox("E-Mail gesendet.", MsgBoxStyle.Information, Title:="Information")
                System.Console.WriteLine("Erfolgreich!")
                Return True
            Else
                System.Console.WriteLine(csv)
                Threading.Thread.Sleep(1000)
                '  System.Console.WriteLine("Programm beendet in 5")
                ' Threading.Thread.Sleep(1000)
                ' System.Console.WriteLine("Programm beendet in 4")
                '  Threading.Thread.Sleep(1000)
                System.Console.WriteLine("Programm beendet in 3")
                Threading.Thread.Sleep(1000)
                System.Console.WriteLine("Programm beendet in 2")
                Threading.Thread.Sleep(1000)
                System.Console.WriteLine("Programm beendet in 1")
                Threading.Thread.Sleep(1000)
            End If
        Catch ex As Exception
            MsgBox(Err.Number & ex.Message & ex.StackTrace.ToString) 'Falls ein Fehler auftritt wird eine MsgBox angezeigt
        End Try
        Return False
    End Function



    Public Function genCSV(von, bis) As String
        Try

          
            Dim sqlstr = " SELECT CASE [BelegartenNr]	WHEN 71     THEN 'GS' " &
                                 " WHEN 70		THEN 'RG' " &
                                    " END AS [BelegArt] " &
                            " ,[RechnungsNr] " &
                            " ,CONVERT(VARCHAR(10), [RechnungsDatum], 104) as [RechnungsDatum] " &
                            "  ,[FilialenNr],[AbfertigungsNr],[UnterNr] " &
                            " ,CONVERT(VARCHAR(10), [Abfertigungsdatum], 104) as [Abfertigungsdatum] " &
                            " ,isnull(Adressen.WölflKundenNr,'') as WölflKundenNr " &
                            " ,CASE  WHEN [EmpfängerStraße] IS NULL      THEN [EmpfängerName 1] " &
                                    " ELSE		 [EmpfängerName 1] + ' ' +[EmpfängerName 2]  " &
                                    " END AS [Empfänger] " &
                            " ,CASE WHEN [EmpfängerStraße] IS NULL       THEN [EmpfängerName 2] " &
                                    " ELSE		[EmpfängerStraße] " &
                                    " END AS [EmpfängerAdresse 1] " &
                            " ,[EmpfängerOrt] as [EmpfängerAdresse 2] " &
                            " ,[Packstücke und Warenbezeichnung] as Beschreibung,[LeistungsNr],[LeistungsBez],[Steuersatz %] ,[SteuerpflichtigerGesamtbetrag] as [SteuerpflichtigerGesamtbetrag Netto] " &
                            " ,[SteuerfreierGesamtbetrag],[SteuerpflichtigerBetrag] as [SteuerpflichtigerBetrag Netto] ,[SteuerfreierBetrag] " &
                    " FROM [VERAG].[dbo].[Rechnungsausgang] inner join [VERAG].[dbo].[RechnungsausgangPositionen] on Rechnungsausgang.[RK_ID]=RechnungsausgangPositionen.[RK_ID] " &
                            " inner join [VERAG].[dbo].Adressen on Rechnungsausgang.EmpfängerKundenNr=Adressen.AdressenNr " &
                    " WHERE RechnungsKundenNr = 150000 " &
                            " and RechnungsDatum between '" & von & "' and '" & bis & "'"
            ' MsgBox(sqlstr)
            '  Dim SQL As New System.Data.Sql
            Dim dt As DataTable = loadDgvBySql(sqlstr)


            Dim fn As String = sPath & "WOELFL.csv" '" & Now.ToString("ddMMyyyyHHmmss") & ".csv"
            Dim outFile As IO.StreamWriter = Nothing
            Try
                outFile = My.Computer.FileSystem.OpenTextFileWriter(fn, False)
            Catch ex As Exception
                MsgBox(ex.Message)
                Return "ERROR: Schreibfehler"
            End Try

            System.Console.WriteLine("Vorhandene Datensätze: " & dt.Rows.Count)

            If dt.Rows.Count = 0 Then
                Return "ERROR: KEINE DATEN"
            End If

            Dim clmns As String = ""
            For i = 0 To dt.Columns.Count - 1
                clmns &= dt.Columns(i).ColumnName.ToString().Replace(";", ",") & ";"
            Next

            outFile.WriteLine(clmns)
            For i = 0 To dt.Rows.Count - 1
                clmns = ""
                For j = 0 To dt.Columns.Count - 1
                    Dim o As Object = dt.Rows(i).Item(j).ToString
                    clmns &= dt.Rows(i).Item(j).ToString() & ";"
                Next
                outFile.WriteLine(clmns)
            Next
            outFile.Close()
            Return fn

        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
            Return "ERROR: " & ex.Message
        End Try
    End Function
    Public Function loadDgvBySql(ByVal sql As String) As DataTable
        Try
            Dim myTable = New DataTable()
            Dim conn As New SqlConnection
            conn.ConnectionString = "Data Source=192.168.0.91\SQLFMZOLL;Initial Catalog=VERAG;Integrated Security=false;User ID=test;Password=BmWr501956;"
            conn.Open()

            Using cmd As New SqlCommand(sql, conn)
                Dim dr As SqlDataReader = cmd.ExecuteReader()
                myTable.Load(dr)
                dr.Close()
            End Using
            conn.Close()

            Return myTable
        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
        End Try

        Return Nothing
    End Function

End Module
