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 Public Class clsEmailIMAP Private Shared Logger As DigitalData.Modules.Logging.Logger Private Shared LogConfig As DigitalData.Modules.Logging.LogConfig Sub New(LogConf As LogConfig) LogConfig = LogConf Logger = LogConf.GetLogger End Sub 'Private Shared Sub OnWriteLog(ByVal sender As Object, ByVal e As WriteLogEventArgs) ' Logger.Info(e.Log) 'End Sub Public Function FetchIMAPMessages(Server As String, Port As Integer, Username As String, Password As String, Inbox As String, Optional IsTest As Boolean = False, Optional DeleteinTest As Boolean = False, Optional MoveMailTo As String = "") As Boolean Logger.Debug("Connecting to Server {0}:{1} with user {2}", Server, Port, Username) Try Logger.Debug("Connecting...") Using oClient As New S22.Imap.ImapClient(Server, Port, Username, Password, S22.Imap.AuthMethod.Login, True) If Not oClient.Authed Then Logger.Warn("Connected to server but authentication failed.") Return False End If Logger.Debug("Connection successful") Logger.Debug($"Fetching unseen MessageIds from Inbox: {Inbox}") Dim oMessageIds As IEnumerable(Of UInteger) = oClient.Search(S22.Imap.SearchCondition.Unseen, Inbox) Logger.Debug("Found {0} messages", oMessageIds.Count) Logger.Debug("Fetching messages...") For Each oMessageId As UInteger In oMessageIds Logger.Debug($"Checking message") Dim oMessage = oClient.GetMessage(oMessageId, False, Inbox) Logger.Debug($"Checking message Subject: {oMessage.Subject}, From: {oMessage.From}") Dim oTempPath = Path.GetTempFileName() Dim oResult = WriteMessageToFile(oMessage, oTempPath) Dim oCount As Integer = 0 Dim oMsg As New Message(oTempPath) oCount &= 1 If IsTest = False Then MAIL_LIST.Add(oMsg) Else Logger.Debug($"IMAP-Test Message#: {oCount} - Msgsubject is: {oMsg.Subject} - MsgMessageID is: {oMsg.MessageID}") Logger.Debug($"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($"Message has been deleted!") End If Catch ex As Exception Logger.Warn("Message could not be deleted: " & ex.Message) End Try Try If MoveMailTo <> "" Then Logger.Debug($"Moving to [{MoveMailTo}] is active...") oClient.MoveMessage(oMessageId, MoveMailTo) Logger.Debug($"Successfully moved!") End If Catch ex As Exception Logger.Warn("Message could not be moved: " & ex.Message) End Try Try If IsTest = False Then File.Delete(oTempPath) End If Catch ex As Exception Logger.Error(ex) Logger.Warn("Temp file could not be deleted") End Try Next oClient.Expunge() Logger.Debug("Finished Message-Fetch") End Using Return True Catch ex As Exception Logger.Error(ex) Return False End Try End Function Private Shared Sub OnWriteLog(ByVal sender As Object, ByVal e As WriteLogEventArgs) Logger.Debug(e.Log) End Sub Public Function FetchIMAPMessagesIsoft(Server As String, Port As Integer, Username As String, Password As String, Inbox As String, Optional IsTest As Boolean = False, Optional DeleteinTest As Boolean = False, Optional MoveMailTo As String = "", Optional IsoftLog As String = "") Try Logger.Debug(String.Format("Working on IMAP_COLLECT Independentsoft...")) Dim oClient As New Independentsoft.Email.Imap.ImapClient(Server, Port) If IsoftLog <> "" Then Dim iLogger As New Independentsoft.Email.Logger(IsoftLog) AddHandler iLogger.WriteLog, AddressOf OnWriteLog oClient.Logger = iLogger End If oClient.EnableSsl = True oClient.ValidateRemoteCertificate = False oClient.Connect() Try oClient.Login(Username, Password, AuthenticationType.Login) Catch ex As Exception Try oClient.Login(Username, Password, AuthenticationType.Ntlm) Catch ex1 As Exception Logger.Error(ex) Return False End Try End Try Logger.Debug("Logged in...") oClient.SelectFolder(Inbox) Dim oEnvelopes As Independentsoft.Email.Imap.Envelope() = oClient.ListMessages() Dim oCount As Integer = 0 For i As Integer = 0 To oEnvelopes.Length - 1 If IsNothing(oEnvelopes(i).Subject) Then Logger.Debug("Attention...Subject is nothing!!") End If 'If envelopes(i).Subject.ToString.ToUpper.Contains("[PROCESSMANAGER]") Or envelopes(i).Subject.ToString.ToUpper.Contains("[ADDI]") Then Logger.Info($"Working on email: UniqueID: {oEnvelopes(i).UniqueID} - Subject:{oEnvelopes(i).Subject} - Date {oEnvelopes(i).Date.ToString}") Logger.Debug($"Working on email: UniqueID: {oEnvelopes(i).UniqueID} - Subject:{oEnvelopes(i).Subject} - Date {oEnvelopes(i).Date.ToString}") Dim oMessage As Mime.Message = oClient.GetMessage(oEnvelopes(i).UniqueID) If Not IsNothing(oMessage) Then oCount += 1 MAIL_LIST.Add(oMessage) End If Try If DeleteinTest = True Then Logger.Debug($"Message shall be deleted...") oClient.Delete(oEnvelopes(i).UniqueID) Logger.Debug($"Message has been marked as deleted!") End If Catch ex As Exception Logger.Warn("Message could not be deleted: " & ex.Message) End Try Try If MoveMailTo <> "" Then Logger.Debug($"Moving to [{MoveMailTo}] is active...") oClient.AddMessage(MoveMailTo, oMessage) Logger.Debug($"Successfully moved!") End If Catch ex As Exception Logger.Warn("Message could not be moved: " & ex.Message) End Try Next oClient.Expunge() oClient.Disconnect() If oCount > 0 Then Logger.Debug($"Found [{oCount.ToString}] Messages...") End If ' Logger.Debug($"{oCount.ToString} messages will be worked..") Logger.Debug("IMAP COLLECT Independentsoft finished!") Return True Catch ex As Exception Logger.Error(ex, "Unexpected Error in IMAP COLLECT Independentsoft:") 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 'Public Function TEST_IMAP_COLLECT(INBOXNAME As String, MYMAIL_SERVER As String, MYMAIL_PORT As Integer, MYMAIL_USER As String, MYMAIL_USER_PW As String) ' Try ' Logger.Info(String.Format("Working on TEST_IMAP_COLLECT.....")) ' Dim oLogPath = System.IO.Path.Combine(My.Application.Info.DirectoryPath, "Log\logindependentSoft.txt") ' Logger.Debug($"IsoftLog: {oLogPath}...") ' Dim oindependentLogger As New Independentsoft.Email.Logger(oLogPath) ' Dim oImapClient As New Independentsoft.Email.Imap.ImapClient(MYMAIL_SERVER, MYMAIL_PORT) ' oImapClient.Logger = oindependentLogger ' oImapClient.ValidateRemoteCertificate = False ' oImapClient.Connect() ' Logger.Debug($"oImapClient connected...") ' Try ' oImapClient.Login(MAIL_USER, MAIL_USER_PW, AuthenticationType.Login) ' Catch ex As Exception ' MsgBox($"Unexpected error in (oImapClient.Login): {ex.Message}") ' Logger.Info($"Unexpected error in oImapClient.Login - User: [{MYMAIL_USER}] PW: [{MYMAIL_USER_PW}]") ' Logger.Warn(ex.StackTrace.ToString) ' Logger.Warn(ex.Message) ' oImapClient.Logger.Close() ' Logger.Error(ex) ' Return False ' End Try ' oImapClient.SelectFolder(INBOXNAME) ' Dim oEnvelopes As Independentsoft.Email.Imap.Envelope() = oImapClient.ListMessages() ' For i As Integer = 0 To oEnvelopes.Length - 1 ' If Not IsNothing(oEnvelopes(i).Subject) Then ' 'If envelopes(i).Subject.ToString.ToUpper.Contains("[PROCESSMANAGER]") Or envelopes(i).Subject.ToString.ToUpper.Contains("[ADDI]") Then ' MsgBox($"Working on email: UniqueID: {oEnvelopes(i).UniqueID} - Subject:{oEnvelopes(i).Subject} - Date {oEnvelopes(i).Date.ToString}") ' Dim message As Mime.Message = oImapClient.GetMessage(oEnvelopes(i).UniqueID) ' End If ' Next ' oImapClient.Disconnect() ' oImapClient.Logger.Close() ' Logger.Info("TEST_IMAP_COLLECT finished!") ' Return True ' Catch ex As Exception ' Logger.Info($"Unexpected error in TEST_IMAP_COLLECT - User: [{MYMAIL_USER}] PW: [{MYMAIL_USER_PW}]") ' MsgBox($"Unexpected error in TEST_IMAP_COLLECT: {ex.Message}") ' Logger.Error(ex, "Unexpected Error in TEST_IMAP_COLLECT:") ' Return False ' End Try 'End Function End Class