Imports System.Text
Imports ComponentPro.Net.Mail
Imports ComponentPro.Net

Namespace SendMail
	''' <summary>
	''' Interaction logic for Window1.xaml
	''' </summary>
	Partial Public Class Main
		Inherits Window
		Public Sub New()
            InitializeComponent()

            PopulateEnum(GetType(SecurityMode), cbxMode)
        End Sub

        Private Sub PopulateEnum(ByVal enumType As Type, ByVal ddl As System.Windows.Controls.ComboBox)
            Dim arr As Array = System.Enum.GetValues(enumType)

            For Each item As Object In arr
                ddl.Items.Add(item)
            Next item
        End Sub

		Private Sub btnUpload_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			If String.IsNullOrEmpty(txtTo.Text) Then
				MessageBox.Show("To email cannot be empty", "Error", MessageBoxButton.OK, MessageBoxImage.Stop)
				Return
			End If

			Dim port As Integer
			Try
				port = Integer.Parse(txtPort.Text)
			Catch exc As Exception
				MessageBox.Show("Invalid Port. Error: " & exc.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Stop)
				Return
			End Try
			If port < 0 OrElse port > 65535 Then
				MessageBox.Show("Invalid port number", "Error", MessageBoxButton.OK, MessageBoxImage.Stop)
				Return
			End If

			If txtServer.Text.Length = 0 Then
				MessageBox.Show("Host name cannot be empty", "Error", MessageBoxButton.OK, MessageBoxImage.Stop)
				Return
			End If

            Dim client As New Smtp()

			Try
				client.Connect(txtServer.Text, port, CType(cbxMode.SelectedIndex, ComponentPro.Net.SecurityMode))
				If Not String.IsNullOrEmpty(txtUsername.Text) Then
					client.Authenticate(txtUsername.Text, txtPassword.Text)
				End If

				Dim msg As New MailMessage()
				msg.From = txtFrom.Text
				msg.To = txtTo.Text
				msg.Cc = txtCC.Text
				msg.Bcc = txtBcc.Text
				msg.Subject = txtSubject.Text
				msg.BodyHtml = txtContent.Text

				client.Send(msg)

				client.Disconnect()

				MessageBox.Show("Message has been sent successfully!", "Email sent", MessageBoxButton.OK, MessageBoxImage.Information)
			Catch ex As Exception
				MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Stop)
			End Try
		End Sub
	End Class
End Namespace
