Imports ComponentPro.Net.Mail

Namespace MailSamples
	Partial Public Class MailAttachment
		Inherits Form
		Private ReadOnly _exception As Boolean

		Public Sub New()
			Try
				InitializeComponent()
			Catch exc As ComponentPro.Licensing.Mail.UltimateLicenseException
				MessageBox.Show(exc.Message, "Error")
				_exception = True
				Return
			End Try

			Dim dataDir As String

			' Gets path to the Data folder.
			dataDir = AppDomain.CurrentDomain.BaseDirectory & "..\..\Data"
			If Not System.IO.Directory.Exists(dataDir) Then
				dataDir = AppDomain.CurrentDomain.BaseDirectory & "Data"
			End If

			txtEmailFile.Text = dataDir & "\TestAttachment.eml"
		End Sub

		''' <summary>
		''' Handles the form's Load event.
		''' </summary>
		''' <param name="e"></param>
		Protected Overrides Sub OnLoad(ByVal e As EventArgs)
			MyBase.OnLoad(e)
			If _exception Then
				Me.Close()
			End If
		End Sub

		''' <summary>
		''' Writes a message.
		''' </summary>
		''' <param name="msg">Message to write.</param>
		''' <param name="parameters">Parameters.</param>
		Private Sub WriteLine(ByVal msg As String, ParamArray ByVal parameters() As Object)
			txtResult.Text &= String.Format(msg, parameters) & vbCrLf
			System.Windows.Forms.Application.DoEvents()
		End Sub

		''' <summary>
		''' Clears the output.
		''' </summary>
		Private Sub Clear()
			txtResult.Clear()
			System.Windows.Forms.Application.DoEvents()
		End Sub

		''' <summary>
		''' Extracs attachments from a mail file.
		''' </summary>
		''' <param name="fileName">Mail file name.</param>
		''' <returns>A boolean value indicating whether the extraction is successful.</returns>
		Private Sub ExtractAttachments(ByVal fileName As String)
			Try
				' Load the mail message from disk
				Dim mail As New MailMessage()
				mail.Load(fileName)

				' DecryptData the message if it is encrypted
				If mail.IsEncrypted Then
					If Not mail.Decryptable Then
						WriteLine("Message cannot be decrypted. You do not have the private key.")
						Return
					End If
					mail.Decrypt()
				End If

				' ValidateRequest the signature if the message is signed
				If mail.IsSigned Then
					Dim result As MailSignatureValidationResult = mail.ValidateSignature()
					If result.Valid Then
						WriteLine("The message is signed and the signature is valid.")
					Else
						WriteLine("The message is signed, but the signature is not valid.")
						ShowProblems(result)
					End If
				End If

				WriteLine("Message contains {0} attachments.", mail.Attachments.Count)

				' If message has no attachments, just exit
				If mail.Attachments.Count = 0 Then
					Return
				End If

				For Each attachment As Attachment In mail.Attachments
					' Write the file
					WriteLine("Saving '{0}' ({1}).", attachment.FileName, attachment.MediaType)
					attachment.Save(attachment.FileName)
				Next attachment

				Return
			Catch exc As Exception
				WriteLine("An error occurred: {0}", exc.Message)
			End Try

			Return
		End Sub

		''' <summary>
		''' Handles the Extract button's Click event.
		''' </summary>
		''' <param name="sender">The button object.</param>
		''' <param name="e">The event arguments.</param>
		Private Sub btnExtract_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnExtract.Click
			' Clear logs.
			Clear()
			ExtractAttachments(txtEmailFile.Text)
		End Sub

		''' <summary>
		''' Handles the Browse list file's Click event.
		''' </summary>
		''' <param name="sender">The button object.</param>
		''' <param name="e">The event arguments.</param>
		Private Sub btnBrowseListFile_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnBrowse.Click
			Dim dlg As New OpenFileDialog()
			Try
				dlg.FileName = txtEmailFile.Text
				dlg.Filter = "Internet Email File (*.eml)|*.eml|Outlook files (*.msg)|*.msg|All files (*.*)|*.*"
				dlg.FilterIndex = 1
				dlg.Title = "Select Email File"
				' Show Open file dialog.
				If dlg.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
					Return
				End If

				txtEmailFile.Text = dlg.FileName
			Catch
				MessageBox.Show(dlg.FileName & " is not a valid email file", "Error")
			End Try
		End Sub

		''' <summary>
		''' Displays the list of problems of the message that was not validated successfully.
		''' </summary>
		''' <param name="result">Validation result.</param>
		Public Sub ShowProblems(ByVal result As MailSignatureValidationResult)
			WriteLine("There were following problems:")

			Dim missing() As String = result.MissingSignatureEmails
			If missing.Length > 0 Then
				WriteLine("- The signatures for the following senders are missing:")
				For i As Integer = 0 To missing.Length - 1
					WriteLine("    {0}", missing(i))
				Next i
			End If
		End Sub

		''' <summary>
		''' Handles the Close button's Click event.
		''' </summary>
		''' <param name="sender">The button object.</param>
		''' <param name="e">The event arguments.</param>
		Private Sub btnClose_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClose.Click
			Me.Close()
		End Sub
	End Class
End Namespace