Imports System.Text
Imports System.Web.UI.WebControls
Imports ComponentPro.Net
Imports ComponentPro.Net.Mail

Partial Public Class _Default
	Inherits System.Web.UI.Page
	Private Sub PopulateEnum()
		Dim arr() As Pop3AuthenticationMethod = CType(System.Enum.GetValues(GetType(Pop3AuthenticationMethod)), Pop3AuthenticationMethod())

		For i As Integer = 0 To arr.Length - 1
			ddlAuthentication.Items.Add(New ListItem(arr(i).ToString(), CInt(arr(i)).ToString()))
		Next i

		Dim index As Integer
		If Integer.TryParse(Request.Form("ddlAuthentication"), index) Then
			ddlAuthentication.SelectedIndex = index
		End If
	End Sub

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
		PopulateEnum()
	End Sub

	''' <summary>
	''' Handles the Download button's Click event.
	''' </summary>
	''' <param name="sender">The button object.</param>
	''' <param name="e">The event arguments.</param>
	Protected Sub btnDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
		' Create a new instance of the Pop3Client class.
		Dim client As New Pop3()

		Try
			Dim mailsPath As String = AppDomain.CurrentDomain.BaseDirectory & "Mails\"

			' Create Mails folder to store downloaded messages if it does not exist.
			If Not System.IO.Directory.Exists(mailsPath) Then
				System.IO.Directory.CreateDirectory(mailsPath)
			End If

			Dim sb As New StringBuilder()
			Dim port As Integer = Integer.Parse(txtPort.Text)

			' Connect to the server.
			client.Connect(txtServer.Text, port, CType(ddlSecurityMode.SelectedIndex, SecurityMode))

			' Login to the server.
			Dim ia As Pop3AuthenticationMethod = CType(Integer.Parse(ddlAuthentication.SelectedValue), Pop3AuthenticationMethod)

			client.Authenticate(txtUser.Text, txtPassword.Text, ia)

			' Retrieve a list of message with unique id and sequence number.
			Dim list As Pop3MessageCollection = client.ListMessages(Pop3EnvelopeParts.UniqueId Or Pop3EnvelopeParts.MessageInboxIndex)
			Dim messages As Integer = Integer.Parse(txtMessages.Text)
			If list.Count < messages Then
				messages = list.Count
			End If

			Dim message As Pop3Message
			For i As Integer = 0 To messages - 1
				message = list(i)

				' Get file name.
				Dim filename As String = mailsPath & GetFilename(message.UniqueId) & ".eml"

				' Get new message only.
				If Not System.IO.File.Exists(filename) Then
					client.DownloadMessage(message.MessageInboxIndex, filename)
					sb.AppendFormat("Message {0} downloaded<br>", message.UniqueId)
				End If
			Next i

			sb.AppendFormat("{0} message(s) have been downloaded successfully!", messages)
			lblResult.Text = sb.ToString()
		Catch exc As Exception
			lblResult.Text = String.Format(Nothing, "Exception: {0}", exc.Message)
		Finally
			' Disconnect.
			client.Disconnect()
		End Try
	End Sub

	''' <summary>
	''' Returns a uniquely correct file name from the specified unique message ID.
	''' </summary>
	''' <param name="uniqueId">The unique id.</param>
	''' <returns>The corrected file name.</returns>
	Private Shared Function GetFilename(ByVal uniqueId As String) As String
		' Characters allowed in the filename
		'string allowed = " .-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";            
		Const allowed As String = " .-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

		' Replace invalid charactes with its hex representation
		Dim sb As New StringBuilder()
		For i As Integer = 0 To uniqueId.Length - 1
			If allowed.IndexOf(uniqueId.Chars(i)) < 0 Then
				sb.AppendFormat("_{0:X2}", System.Convert.ToInt32(uniqueId.Chars(i)))
			Else
				sb.Append(uniqueId.Chars(i))
			End If
		Next i
		Return sb.ToString()
	End Function
End Class