Imports Independentsoft.Email Imports Independentsoft.Email.Imap Imports Independentsoft.Email.Mime Imports DigitalData.EMLProfiler.ClassCurrent Imports DigitalData.Modules.Logging Imports AE Imports System.Net Imports System.Reflection Imports System.IO Imports DigitalData.Modules.Database Public Class clsEmailIMAP Private Shared Logger As DigitalData.Modules.Logging.Logger Private Shared LogConfig As DigitalData.Modules.Logging.LogConfig Private _DB_MSSQL As clsDatabase Sub New(LogConf As LogConfig, ECMConnectionString As String) LogConfig = LogConf Logger = LogConf.GetLogger _DB_MSSQL = New clsDatabase(LogConf, ECMConnectionString) End Sub 'Private Shared Sub OnWriteLog(ByVal sender As Object, ByVal e As WriteLogEventArgs) ' Logger.Info(e.Log) 'End Sub Public Function FetchIMAPMessagesS22(Server As String, Port As Integer, Username As String, Password As String, pInbox As String, Optional IsTest As Boolean = False, Optional DeleteinTest As Boolean = False, Optional MoveMailTo As String = "") As Boolean Logger.Debug("FetchIMAPMessagesS22 - Connecting to Server {0}:{1} with user {2}", Server, Port, Username) Try Logger.Debug("FetchIMAPMessagesS22 - Connecting...") Using oClient As New S22.Imap.ImapClient(Server, Port, Username, Password, S22.Imap.AuthMethod.Login, True) If Not oClient.Authed Then Logger.Warn("FetchIMAPMessagesS22 - Connected to server but authentication failed.") Return False End If Logger.Debug($"FetchIMAPMessagesS22 - Fetching unseen MessageIds from Inbox: {pInbox}") Dim oMessageIds As IEnumerable(Of UInteger) = oClient.Search(S22.Imap.SearchCondition.Unseen, pInbox) If oMessageIds.Count > 0 Then Logger.Info("FetchIMAPMessagesS22 - Found [{0}] messages", oMessageIds.Count) Logger.Debug("FetchIMAPMessagesS22 - Fetching messages...") End If Dim oMessageCountRegular As Integer = 0 Dim oMessageCountWorked As Integer = 0 Dim oLastLog As String For Each oMessageId As UInteger In oMessageIds Logger.Debug($"Checking message...") Dim oMessage = oClient.GetMessage(oMessageId, False, pInbox) oLastLog = $"Checking message with Subject [{oMessage.Subject}] From [{oMessage.From}]" Logger.Debug(oLastLog) Dim oTempPath = Path.GetTempFileName() Try Dim oResult = WriteMessageToFile(oMessage, oTempPath) oLastLog &= $" # Message written to TempPath [{oTempPath}]" Dim oMessageREFGUID Dim oMsg As Message Try oLastLog &= " # Creating the New Message(oTempPath)" oMsg = New Message(oTempPath) oLastLog &= " # Extracting the MessageID" oMessageREFGUID = oMsg.MessageID Catch ex As Exception Logger.Warn($"FetchIMAPMessagesS22 - Could not get a MessageID or create a MailObject - Error: {ex.Message} - Last Debug Log: [{oLastLog}]") Continue For End Try oLastLog &= " # Got the MessageID" oMessageREFGUID = oMessageREFGUID.Replace(">", "").Replace("<", "") Dim oCHECKSQL = $"SELECT * FROM TBEMLP_HISTORY WHERE EMAIL_MSGID = '{oMessageREFGUID}'" Dim oCHECKDT As DataTable = _DB_MSSQL.Return_Datatable(oCHECKSQL) If Not IsNothing(oCHECKDT) Then If oCHECKDT.Rows.Count = 0 Then oMessageCountRegular += 1 CURRENT_WORKMAIL_LIST.Add(oMsg) oLastLog &= " # Added to CURRENT_WORKMAIL_LIST" Else Logger.Info("FetchIMAPMessagesS22 - Message has already been worked! Skipping!") Logger.Debug($"Message shall be deleted...") oLastLog &= " # Message shall be deleted..." oClient.DeleteMessage(oMessageId) Logger.Debug($"FetchIMAPMessagesS22 - Message has been deleted!") oLastLog &= " # FetchIMAPMessagesS22 - Message has been deleted!" Dim oUpd = $"UPDATE TBEMLP_HISTORY SET DATE_DELETED_INBOX = GETDATE() WHERE EMAIL_MSGID = '{oMessageId}'" _DB_MSSQL.Execute_non_Query(oUpd) oMessageCountWorked += 1 End If If IsTest = True Then Logger.Debug($"FetchIMAPMessagesS22 - IMAP-Test Message#: {oMessageCountRegular} - Msgsubject is: {oMsg.Subject} - MsgMessageID is: {oMessageREFGUID}") Logger.Debug($"FetchIMAPMessagesS22 - message correctly fetched. Mail has been downloaded to {oTempPath}") End If Try If DeleteinTest = True Then Logger.Debug($"Message shall be deleted...") oClient.DeleteMessage(oMessageId,) Logger.Debug($"FetchIMAPMessagesS22 - Message has been deleted!") End If Catch ex As Exception Logger.Warn("Message could not be deleted: " & ex.Message) End Try If MoveMailTo <> String.Empty Then Try Logger.Debug($"Moving to [{MoveMailTo}] is active...") oClient.MoveMessage(oMessageId, MoveMailTo) Logger.Debug($"FetchIMAPMessagesS22 - successfully moved!") Catch ex As Exception Logger.Warn($"FetchIMAPMessagesS22 - Could not move message to folder [{MoveMailTo}] - Error: {ex.Message}") End Try End If End If Try If IsTest = False Then File.Delete(oTempPath) End If Catch ex As Exception End Try Catch ex As Exception Logger.Warn($"FetchIMAPMessages - Unexpected Error while working on email: [{ex.Message}] - Last Debug Log: [{oLastLog}]") End Try Next oClient.Expunge() Logger.Debug("FetchIMAPMessagesS22 - Finished Message-Fetch") If oMessageCountRegular > 0 Or oMessageCountWorked > 0 Then Logger.Info($"###############################################") If oMessageCountRegular > 0 Then Logger.Info($"Found [{oMessageCountRegular.ToString}] regular messages to work on!") End If If oMessageCountWorked > 0 Then Logger.Info($"Found [{oMessageCountWorked.ToString}] worked messages to work on!") End If If IsTest = True Then Dim omsgtext As String If oMessageCountRegular > 0 Then omsgtext = $"Found [{oMessageCountRegular.ToString}] regular Messages to work on!" End If If oMessageCountWorked > 0 Then If omsgtext = String.Empty Then Logger.Info($"Found [{oMessageCountWorked.ToString}] worked messages to work on!") Else omsgtext += vbNewLine & $"Found [{oMessageCountWorked.ToString}] worked messages to work on!" End If End If MsgBox(omsgtext) End If Logger.Info($"###############################################") End If End Using Return True Catch ex As Exception Logger.Error(ex) Return False End Try End Function ''' ''' Uses a private API from MailWriter to write a MailMessage to disk. ''' May break in future versions of .NET ''' Public Function WriteMessageToFile(Message As Mail.MailMessage, Filename As String) As Boolean Dim oAssembly As Assembly = GetType(Mail.SmtpClient).Assembly Dim oMailWriterType As Type = oAssembly.[GetType]("System.Net.Mail.MailWriter") Try Using oStream As New FileStream(Filename, FileMode.Create) Dim oMailWriterConstructor As ConstructorInfo = oMailWriterType.GetConstructor( BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, New Type() {GetType(Stream)}, Nothing ) Dim oMailWriter As Object = oMailWriterConstructor.Invoke(New Object() {oStream}) Dim sendMethod As MethodInfo = GetType(Mail.MailMessage).GetMethod("Send", BindingFlags.Instance Or BindingFlags.NonPublic) sendMethod.Invoke(Message, BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, {oMailWriter, True, True}, Nothing) End Using Return True Catch ex As Exception Return Nothing End Try End Function End Class