EMailProfiler.Common: Neue Extract Attachments-Logik & InfoMail Logik

This commit is contained in:
2024-09-25 16:08:51 +02:00
parent b18a6a3045
commit c91a7b82c7
9 changed files with 549 additions and 81 deletions

View File

@@ -14,6 +14,7 @@ Imports DigitalData.Modules.Patterns
Imports System.Data.SqlClient
Imports GdPicture14
Imports Limilabs.Client.IMAP
Imports System.Net.NetworkInformation
Public Class clsWorkEmail
Private Const SUBJECT_MAX_LENGTH = 25
@@ -46,6 +47,12 @@ Public Class clsWorkEmail
Private ReadOnly _RejectionTemplateId As Integer = 0
Private ReadOnly _InfoTemplateId As Integer = 0
Private ReadOnly _LicenseManager As New LicenseManager
Private ReadOnly _ValidExtensions As List(Of String)
Private ReadOnly _GraphicExtensions As List(Of String)
Private _worked_email As Boolean = False
Sub New(LogConf As LogConfig, ConStr As String, WmConStr As String, pUseWindream As Boolean, EmailAccountID As Integer, EmlProfPraefix As String, pRejectionTemplateId As Integer, pInfoTemplateId As Integer)
@@ -60,6 +67,8 @@ Public Class clsWorkEmail
_InfoTemplateId = pInfoTemplateId
_Logger.Debug($"_RejectionTemplateId: {_RejectionTemplateId}")
_ValidExtensions = New List(Of String) From {"pdf", "xls", "xlsx", "doc", "docx", "ppt", "pptx"}
_GraphicExtensions = New List(Of String) From {"jpg", "bmp", "jpeg", "gif", "png", "xml"}
If pUseWindream Then
_windream = New clsWindream_allgemein(LogConf)
@@ -67,6 +76,8 @@ Public Class clsWorkEmail
_windreamConnectionString = WmConStr
End If
_LicenseManager.RegisterKEY(GDPictureLicense)
_EmailAccountID = EmailAccountID
SUBJECT_PRAFIX = EmlProfPraefix
Catch ex As Exception
@@ -214,9 +225,11 @@ Public Class clsWorkEmail
If IS_LOCAL_TEST = False Then
InsertHistoryEntry(CurrentMail)
End If
End If
Return True
' Jetzt werden die ggf gefundenen Attachment-Fehler überprüft und verarbeitet
SendMailToSenderIfAttachmentsAreNotValid()
Return True
End If
End If
@@ -226,6 +239,85 @@ Public Class clsWorkEmail
End Try
End Function
''' <summary>
''' Wenn beim Herauslösen der Attachments festgestellt wurde,
''' das ein Teil der Attachments fehlerhaft war, wird der Absender hier
''' darüber informiert.
''' </summary>
Private Sub SendMailToSenderIfAttachmentsAreNotValid()
Dim oHtmlFilenameList As String = GetHtmlFilenameList()
If oHtmlFilenameList.IsNotNullOrEmpty() Then
AddToEmailQueueMSSQL(CurrentMail.MessageId, "", "Attachment invalid", _EmailAccountID, _InfoTemplateId, ErrorCode.PDFStructureCorrupt, oHtmlFilenameList, "")
End If
End Sub
''' <summary>
''' Stellt die Dateinamen der Dateien zusammen, die nicht valide sind.
''' Die Ausgabe erfolgt als HTML-Liste
''' </summary>
Private Function GetHtmlFilenameList() As String
Dim filenameHtmlString As String = String.Empty
Dim oComment As String = String.Empty
For Each attachmentItem In EmailAttachments
If attachmentItem.SendInfoMailNecessary = True Then
oComment = GetErrorCodeComment(attachmentItem.ErrorCodeValue)
AddTrackingStatusMSSQL(CurrentMail.MessageId, attachmentItem.OrgFileName, "FILE CONSISTENCY NOT OK", oComment, "EMail Profiler")
filenameHtmlString += "<li>" + attachmentItem.OrgFileName + "</li>"
End If
' prüfe evtl. eingebettete Anhänge
Dim embeddedFilenamesHtmlString As String = String.Empty
If attachmentItem.EmbeddedFiles.Count > 0 Then
For Each embeddedItem In attachmentItem.EmbeddedFiles
If embeddedItem.SendInfoMailNecessary = True Then
oComment = GetErrorCodeComment(embeddedItem.ErrorCodeValue)
AddTrackingStatusMSSQL(CurrentMail.MessageId, embeddedItem.OrgFileName, "EMBEDDED FILE CONSISTENCY NOT OK", oComment, "EMail Profiler")
embeddedFilenamesHtmlString += "<li>" + embeddedItem.OrgFileName + "</li>"
End If
Next
If embeddedFilenamesHtmlString.IsNotNullOrEmpty() Then
embeddedFilenamesHtmlString = "<ul>" + embeddedFilenamesHtmlString + "</ul>"
End If
End If
If embeddedFilenamesHtmlString.IsNotNullOrEmpty() Then
filenameHtmlString += embeddedFilenamesHtmlString
End If
Next
If filenameHtmlString.IsNotNullOrEmpty() Then
filenameHtmlString = "<ul>" + filenameHtmlString + "</ul>"
End If
Return filenameHtmlString
End Function
Private Function GetErrorCodeComment(errorCodeValue As ErrorCode) As String
Dim retValue As String = String.Empty
If errorCodeValue = ErrorCode.FileExtensionNotValid Then
retValue = "File Extension not valid"
ElseIf errorCodeValue = ErrorCode.PDFStructureCorrupt Then
retValue = "PDF Structure corrupt"
End If
Return retValue
End Function
''' <summary>
''' Method to decide wether we use the old or the new
''' Rejection E-mail method.
@@ -567,8 +659,8 @@ Public Class clsWorkEmail
If COPY2HDD(pCurrentMail, oRow("COPY_2_HDD"), oRow("PATH_ORIGINAL"), oRow("PATH_EMAIL_ERRORS"), True) = True Then
If EXTRACT_ATTACHMENTS(pCurrentMail, oExtractMainPath, oRow("PATH_EMAIL_ERRORS")) = True Then
'If EXTRACT_ATTACHMENTS(pCurrentMail, oExtractMainPath, oRow("PATH_EMAIL_ERRORS")) = True Then
If ExtractAttachments(pCurrentMail, oExtractMainPath) = True Then
Return True
Else
_Logger.Warn("!##Returning false from EXTRACT_ATTACHMENTS!##")
@@ -577,11 +669,8 @@ Public Class clsWorkEmail
Else
Return False
End If
Next
Return True
Catch ex As Exception
_Logger.Error(ex)
@@ -802,6 +891,222 @@ Public Class clsWorkEmail
Return False
End Try
End Function
Private Function ExtractAttachments(pCurrentMail As MailContainer, pExtractPath As String) As Boolean
_Logger.Debug("In ExtractAttachments - pExtractPath = [{0}]", pExtractPath)
CURRENT_ATTMT_COUNT = 0
TEMP_WORK_FILES.Clear()
EmailAttachments.Clear()
If String.IsNullOrEmpty(CurrentTempMailPath) Then
_Logger.Warn("ExtractAttachments() CurrentTempMailPath is NOTHING")
Return True
End If
If File.Exists(CurrentTempMailPath) = False Then
_Logger.Warn($"ExtractAttachments() {CurrentTempMailPath} not existing")
Return True
End If
Dim oExtractTempPath As String = GetExtractTempPath(pExtractPath)
If String.IsNullOrEmpty(oExtractTempPath) Then
_Logger.Warn("ExtractAttachments() oExtractTempPath is NOTHING")
Return True
End If
Dim oAttachmentCount As Integer = 0
For Each oAttachment As MimeData In pCurrentMail.Mail.Attachments
_Logger.Info("Working on Attachment [{0}]", oAttachment.SafeFileName)
Dim oEmailAttachment As EmailAttachment = New EmailAttachment() With
{
.OrgFileName = oAttachment.SafeFileName
}
EmailAttachments.Add(oEmailAttachment)
If ValidateFileExtension(oEmailAttachment) = False Then
Continue For
End If
oEmailAttachment.DestFileName = $"{pCurrentMail.MessageId}~Attm{oAttachmentCount}{oEmailAttachment.Extension}"
_Logger.Debug("Final Filename for Attachment: [{0}]", oEmailAttachment.DestFileName)
oEmailAttachment.DestFilePath = Path.Combine(oExtractTempPath, oEmailAttachment.DestFileName)
_Logger.Debug("Final Path for Attachment: [{0}]", oEmailAttachment.DestFilePath)
If CleanUpFilePath(oEmailAttachment.DestFilePath) = False Then
_Logger.Warn("ExtractAttachments() Could not clean up filepath!")
MESSAGE_ERROR = True
Continue For
End If
' Sichere Datei auf Platte
If SaveFileToDisk(oAttachment, oEmailAttachment.DestFilePath) = True Then
_Logger.Info(String.Format("Attachment saved to [{0}]", oEmailAttachment.DestFilePath))
' Schreibe Satz nach EMLP_HISTORY
If (InsertAttachmentHistoryEntry(pCurrentMail, oEmailAttachment.OrgFileName, oEmailAttachment.DestFileName)) = True Then
oAttachmentCount += 1
End If
Else
_Logger.Warn($"Error while saving AttachmentName: {oEmailAttachment.DestFilePath}")
MESSAGE_ERROR = True
Continue For
End If
' Verarbeite PDF Files
If oEmailAttachment.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase) = True Then
Dim oGdPicturePDF As New GdPicturePDF()
Dim oStatus As GdPictureStatus = oGdPicturePDF.LoadFromFile(oEmailAttachment.DestFilePath, True)
If oStatus = GdPictureStatus.OK Then
' Verarbeite Embedded Attachments
WorkEmbeddedAttachments(oEmailAttachment, oGdPicturePDF)
Else
oAttachmentCount -= 1
CleanUpFilePath(oEmailAttachment.DestFilePath)
oEmailAttachment.FileStatus = oStatus
oEmailAttachment.ErrorCodeValue = ErrorCode.PDFStructureCorrupt
oEmailAttachment.SendInfoMailNecessary = True
MESSAGE_ERROR = True
Continue For
End If
End If
TEMP_WORK_FILES.Add(oEmailAttachment.DestFilePath)
Next
CURRENT_ATTMT_COUNT = oAttachmentCount
If MESSAGE_ERROR = True Then
WorkTempFiles("delete")
Return False
End If
WorkTempFiles("move")
Return True
End Function
Private Sub WorkEmbeddedAttachments(pEmailAttachment As EmailAttachment, pGDPicturePDF As GdPicturePDF)
Dim embeddedFileCount As Integer = pGDPicturePDF.GetEmbeddedFileCount()
If embeddedFileCount <= 0 Then
' nothing to do
Return
End If
For i As Integer = 0 To embeddedFileCount - 1
Dim oEmbAttName As String = pGDPicturePDF.GetEmbeddedFileName(i)
Dim oEmbeddedFile As EmailAttachment = New EmailAttachment() With
{
.OrgFileName = oEmbAttName
}
pEmailAttachment.EmbeddedFiles.Add(oEmbeddedFile)
oEmbeddedFile.FileStatus = pGDPicturePDF.GetStat()
If oEmbeddedFile.FileStatus = GdPictureStatus.OK Then
If ValidateFileExtension(oEmbeddedFile) = False Then
Continue For
End If
Dim FileSize As Integer = pGDPicturePDF.GetEmbeddedFileSize(i)
If pGDPicturePDF.GetStat() = GdPictureStatus.OK Then
Dim FileData As Byte() = New Byte(FileSize) {}
Dim status As GdPictureStatus = pGDPicturePDF.ExtractEmbeddedFile(0, FileData)
oEmbeddedFile.FileStatus = status
If status <> GdPictureStatus.OK Or FileSize = 0 Then
oEmbeddedFile.ErrorCodeValue = ErrorCode.PDFStructureCorrupt
oEmbeddedFile.SendInfoMailNecessary = True
Continue For
End If
End If
End If
Next
End Sub
Private Function SaveFileToDisk(pAttachment As MimeData, pAttachmentFilePath As String) As Boolean
Try
_Logger.Debug(String.Format("Trying to save attachment [{0}]", pAttachmentFilePath))
pAttachment.Save(pAttachmentFilePath)
Dim oFileInfo As New FileInfo(pAttachmentFilePath)
Dim oFileLength As Long = oFileInfo.Length
If oFileLength <= 2 Then
_Logger.Warn($"##!! oFileLength for AttachmentObjects is <=2 !!##")
CleanUpFilePath(pAttachmentFilePath)
Return False
End If
Return True
Catch ex As Exception
_Logger.Error(ex)
Return False
End Try
End Function
Private Function CleanUpFilePath(pFilePath As String) As Boolean
Try
If File.Exists(pFilePath) Then
_Logger.Info("File [{0}] will be deleted!", pFilePath)
File.Delete(pFilePath)
End If
Return True
Catch ex As Exception
_Logger.Error(ex)
Return False
End Try
End Function
Private Function GetExtractTempPath(pExtractPath As String) As String
Try
Dim oExtractTempPath = Path.Combine(pExtractPath, "Temp")
If Directory.Exists(oExtractTempPath) = False Then
Directory.CreateDirectory(oExtractTempPath)
End If
Return oExtractTempPath
Catch ex As Exception
_Logger.Error(ex)
Return String.Empty
End Try
End Function
Private Function ValidateFileExtension(pAttachmentData As EmailAttachment) As Boolean
_Logger.Debug("Validate extension of [{0}]", pAttachmentData.OrgFileName)
Dim lowerFilename = pAttachmentData.OrgFileName.ToLower
Dim oIsValidExtension = _ValidExtensions.Any(Function(ext) lowerFilename.EndsWith(ext))
Dim oIsGraphicExtension = _GraphicExtensions.Any(Function(ext) lowerFilename.EndsWith(ext))
If oIsValidExtension = False Then
pAttachmentData.IsValidExtension = False
If oIsGraphicExtension = False Then
_Logger.Warn("File has no valid extension, and it has no graphic extension. In this case we have to inform the sender!")
pAttachmentData.SendInfoMailNecessary = True
pAttachmentData.ErrorCodeValue = ErrorCode.FileExtensionNotValid
End If
Return False
End If
Return True
End Function
Private Function EXTRACT_ATTACHMENTS(pCurrentMail As MailContainer, pExtractPath As String, pErrorPath As String)
_Logger.Debug("In EXTRACT_ATTACHMENTS...")
@@ -981,24 +1286,26 @@ Public Class clsWorkEmail
Return False
End Try
End Function
Private Sub WorkTempFiles(pACT As String)
Private Sub WorkTempFiles(pAction As String)
For Each _file In TEMP_WORK_FILES
_Logger.Debug("Working ({0}) on temp work file: [{1}]", pACT, _file)
If File.Exists(_file) Then
If pACT = "Delete" Then
Try
_Logger.Debug("Working ({0}) on temp work file: [{1}]", pAction, _file)
Try
If File.Exists(_file) Then
If pAction = "Delete" Then
File.Delete(_file)
Catch ex As Exception
_Logger.Error(ex)
_Logger.Warn("Could not delete the tempworkfile : [{0}]", _file)
End Try
ElseIf pACT = "move" Then
File.Move(_file, _file.Replace("\Temp", ""))
End If
ElseIf pAction = "move" Then
File.Move(_file, _file.Replace("\Temp", ""))
End If
End If
End If
Catch ex As Exception
_Logger.Error(ex)
_Logger.Warn("Could not delete/move the tempworkfile : [{0}]", _file)
MESSAGE_ERROR = True
End Try
Next
TEMP_WORK_FILES.Clear()
End Sub