general clean up, add file contents to getdocumentbyx methods

This commit is contained in:
Jonathan Jenne
2019-04-10 16:15:00 +02:00
parent dee5d33bb9
commit 696a8ddbf6
12 changed files with 196 additions and 44 deletions

View File

@@ -1,20 +1,148 @@
Imports Independentsoft.Email
Imports Independentsoft.Email.Pop3
Imports Independentsoft.Email.Smtp
Imports Independentsoft.Email.Mime
Imports Independentsoft.Email.Imap
Imports DigitalData.Modules.Logging
Imports System.Net.Mail
Imports System.Net
Imports System.Reflection
Imports System.IO
Public Class Email
Private _logger As Logging.Logger
Private _logConfig As LogConfig
Private ReadOnly _logger As Logging.Logger
Private ReadOnly _logConfig As LogConfig
Public Sub New(LogConfig As LogConfig)
_logger = LogConfig.GetLogger()
_logConfig = LogConfig
End Sub
''' <summary>
''' Tests connection to a given IMAP Server by connecting and doing a simple message query.
''' </summary>
''' <param name="Server">IP-Address or Domainname of Server</param>
''' <param name="Port">IMAP-Port</param>
''' <param name="Username">IMAP-Username</param>
''' <param name="Password">IMAP-Password</param>
''' <param name="Folder">The folder to fetch messages from. Defaults to `Inbox`</param>
''' <returns>True if connection and query were successful. False otherwise.</returns>
Public Function TestIMAPLogin(Server As String, Port As Integer, Username As String, Password As String, Optional Folder As String = "Inbox") As Boolean
_logger.Debug("Testing Login 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 MessageIds..")
Dim oMessageIds As IEnumerable(Of UInteger) = oClient.Search(S22.Imap.SearchCondition.Unseen, Folder)
_logger.Debug("Found {0} messages", oMessageIds.Count)
_logger.Debug("Fetching messages...")
Dim oMessages As IEnumerable(Of MailMessage) = oClient.GetMessages(oMessageIds, False, Folder)
_logger.Debug("Messages fetched")
oClient.Dispose()
Return True
End Using
Catch ex As Exception
_logger.Error(ex)
Return False
End Try
End Function
''' <summary>
''' Connects to an IMAP Server with the given credentials and
''' fetches emails from the given folder.
''' Results can be filtered with `SearchCondition`
''' </summary>
''' <param name="Server">IP-Address or Domainname of Server</param>
''' <param name="Port">IMAP-Port</param>
''' <param name="Username">IMAP-Username</param>
''' <param name="Password">IMAP-Password</param>
''' <param name="Folder">The folder to fetch messages from</param>
''' <param name="SearchCondition">Filter the search command. Defaults to `All`</param>
''' <returns>A list of Independentsoft.Email.Mime.Message objects</returns>
Public Function FetchIMAPMessages(Server As String, Port As Integer, Username As String, Password As String, Folder As String, Optional SearchCondition As S22.Imap.SearchCondition = S22.Imap.SearchCondition.All) As List(Of Message)
Dim oMessages As New List(Of Message)
_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 Nothing
End If
_logger.Debug("Connection successful")
_logger.Debug("Fetching MessageIds..")
Dim oMessageIds As IEnumerable(Of UInteger) = oClient.Search(S22.Imap.SearchCondition.Unseen, Folder)
_logger.Debug("Found {0} messages", oMessageIds.Count)
_logger.Debug("Fetching messages...")
' Since this needs to return a list of IndependentSoft Message objects,
' we 'convert' the .NET MailMessage objects that are fetched from the server
' by writing them temporarily to disk as an eml file and then reading them back into a Message object.
' This approach uses an unintended use of internal .NET APIs and may break in the future.
For Each oMessageId As UInteger In oMessageIds
Dim oMessage = oClient.GetMessage(oMessageId, False, Folder)
Dim oTempPath = Path.GetTempFileName()
Dim oResult = WriteMessageToFile(oMessage, oTempPath)
Dim oMsg As New Message(oTempPath)
oMessages.Add(oMsg)
Try
File.Delete(oTempPath)
Catch ex As Exception
_logger.Error(ex)
_logger.Warn("Temp file could not be deleted")
End Try
Next
_logger.Debug("{0} Messages fetched", oMessages.Count)
End Using
Return oMessages
Catch ex As Exception
_logger.Error(ex)
Return Nothing
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 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(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 IMAP_COLLECT(INBOXNAME As String, MYMAIL_SERVER As String, MYMAIL_PORT As Integer, MYMAIL_USER As String, MYMAIL_USER_PW As String)
Try
Dim oMAIL_LIST As New ArrayList()

View File

@@ -53,6 +53,9 @@
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.5.11\lib\net45\NLog.dll</HintPath>
</Reference>
<Reference Include="S22.Imap, Version=3.6.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\S22.Imap.3.6.0.0\lib\net40\S22.Imap.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" />

View File

@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NLog" version="4.5.11" targetFramework="net461" />
<package id="S22.Imap" version="3.6.0.0" targetFramework="net461" />
</packages>