270 lines
12 KiB
VB.net
270 lines
12 KiB
VB.net
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 <> "" And LogConfig.Debug = True 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
|
|
Logger.Warn("Error while loginImap.now trying Ntlm-Auth: " & ex.Message)
|
|
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 coSearchCriteria As New SearchCriteria()
|
|
coSearchCriteria.Unseen = True
|
|
Dim oCount As Integer = 0
|
|
Dim oUniqueID As Integer() = oClient.Search(coSearchCriteria)
|
|
|
|
If IsTest = True Then
|
|
MsgBox($"{oUniqueID.Count} unseen messages! (oUniqueID.Length: {oUniqueID.Length.ToString})")
|
|
Dim oFoundMessages1 As Message() = New Message(oUniqueID.Length - 1) {}
|
|
|
|
For i As Integer = 0 To oUniqueID.Length - 1
|
|
oFoundMessages1(i) = oClient.GetMessage(oUniqueID(i))
|
|
MsgBox($"Message {i.ToString} - {oFoundMessages1(i).Subject}...")
|
|
Next
|
|
End If
|
|
|
|
Dim oFoundMessages As Message() = New Message(oUniqueID.Length - 1) {}
|
|
Dim oEnvelopes As Independentsoft.Email.Imap.Envelope() = oClient.ListMessages()
|
|
For oCounterEnvelope As Integer = 0 To oEnvelopes.Length - 1
|
|
For oCounterUnseen As Integer = 0 To oUniqueID.Length - 1
|
|
If oEnvelopes(oCounterEnvelope).UniqueID = oUniqueID(oCounterUnseen) Then
|
|
Dim oMSG = $"Working on unseen email: UniqueID [{oEnvelopes(oCounterEnvelope).UniqueID}] - Subject[{oEnvelopes(oCounterEnvelope).Subject}] - Date [{oEnvelopes(oCounterEnvelope).Date.ToString}]"
|
|
If IsTest = True Then
|
|
MsgBox(oMSG)
|
|
End If
|
|
Logger.Info(oMSG)
|
|
Logger.Debug(oMSG)
|
|
Dim oMessage As Mime.Message = oClient.GetMessage(oEnvelopes(oCounterEnvelope).UniqueID)
|
|
If Not IsNothing(oMessage) Then
|
|
oCount += 1
|
|
MAIL_LIST.Add(oMessage)
|
|
oClient.Store(oEnvelopes(oCounterEnvelope).UniqueID, "+FLAGS", "SEEN")
|
|
End If
|
|
End If
|
|
Next
|
|
Next
|
|
oClient.Expunge()
|
|
oClient.Disconnect()
|
|
If oCount > 0 Then
|
|
Logger.Debug($"###############################################")
|
|
Logger.Debug($"Found [{oCount.ToString}] Messages to work on!")
|
|
Logger.Debug($"###############################################")
|
|
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
|
|
Public Function IMAP_Set2Seen(Server As String, Port As Integer, Username As String, Password As String, IsoftLog As String)
|
|
Try
|
|
Logger.Debug(String.Format("Working on IMAP_Set2Seen Independentsoft..."))
|
|
Dim oClient As New Independentsoft.Email.Imap.ImapClient(Server, Port)
|
|
If IsoftLog <> "" And LogConfig.Debug = True 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
|
|
Logger.Warn("Error while loginImap.now trying Ntlm-Auth: " & ex.Message)
|
|
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 coSearchCriteria As New SearchCriteria()
|
|
coSearchCriteria.Unseen = True
|
|
|
|
Dim oUniqueID As Integer() = oClient.Search(coSearchCriteria)
|
|
|
|
Dim oFoundMessages As Message() = New Message(oUniqueID.Length - 1) {}
|
|
|
|
For i As Integer = 0 To oUniqueID.Length - 1
|
|
oFoundMessages(i) = oClient.GetMessage(oUniqueID(i))
|
|
If oFoundMessages(i).Subject.ToLower.Contains("seen") Then
|
|
Logger.Debug($"Working on unseen email: [{oUniqueID(i)}] Subject:{oFoundMessages(i).Subject} - Date {oFoundMessages(i).Date}")
|
|
Dim oEnvelopes1 As Independentsoft.Email.Imap.Envelope() = oClient.ListMessages()
|
|
For i1 As Integer = 0 To oEnvelopes1.Length - 1
|
|
If oEnvelopes1(i1).UniqueID = oUniqueID(i) Then
|
|
Logger.Debug($"Setting email to Unseen!")
|
|
oClient.Store(oEnvelopes1(i1).UniqueID, "+FLAGS", "SEEN")
|
|
MsgBox("Set to SEEN")
|
|
End If
|
|
|
|
Next
|
|
End If
|
|
|
|
Next
|
|
oClient.Expunge()
|
|
MsgBox("Expunge done")
|
|
oClient.Disconnect()
|
|
|
|
|
|
Logger.Debug("IMAP_Set2Seen finished!")
|
|
Return True
|
|
Catch ex As Exception
|
|
Logger.Error(ex, "Unexpected Error in IMAP_Set2Seen Independentsoft:")
|
|
Return False
|
|
End Try
|
|
End Function
|
|
|
|
''' <summary>
|
|
''' Uses a private API from MailWriter to write a MailMessage to disk.
|
|
''' May break in future versions of .NET
|
|
''' </summary>
|
|
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
|