I need some help please. I am trying to write code to send emails from a .txt file. The problem I am having is sending an email when there is an invalid formatted emailaddress string. it appears from the documentation that .net has a built in validator and will throw an exception when an address is not in the correct format. I want to be able to either only add valid emailaddress's to my array or skip the invalid address when I start my for each loop. the way my code is now sending stops upon an invalid emailaddress and I am not sure how to write the code properly to continue the For Each and only count the successful emails sent,any help would be appreciated
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
emailadd.Clear()
GetEmailAdd() 'function to readtable from txt file
Dim attach As Attachment = Nothing
If CheckBox1.Checked Then
Dim filename As String = OpenFileDialog2.FileName
attach = New Attachment(filename)
End If
Dim i As Integer = 0
Dim pauseTime As Integer = CDbl(txttimesecs.Text) * 1000
Dim result As DialogResult = MessageBox.Show("There are" & " " & emailadd.Count & " " & "Messages to be Sent", "Send Email", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
If result = DialogResult.Cancel Then
Return
End If
For Each email In emailadd
Try
Dim sslValue As String = ComboBox1.Text
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New Net.NetworkCredential(txtusername.Text, txtpassword.Text)
SmtpServer.Port = CDbl(txtserverport.Text)
SmtpServer.Host = txtservername.Text
SmtpServer.EnableSsl = sslValue
mail = New MailMessage()
mail.From = New MailAddress(txtfrom.Text)
mail.To.Add(email)
mail.Subject = txtsubj.Text
If CheckBox1.Checked Then
mail.Attachments.Add(attach)
End If
mail.Body = txtmsgbox.Text
If btnhtml.Checked = True Then
mail.IsBodyHtml = True
Else
mail.IsBodyHtml = False
End If
SmtpServer.Send(mail)
i += 1
Catch ex As Exception
MsgBox(ex.ToString)
MsgBox("No Messages Sent")
Return
End Try
wait(pauseTime)
Next
MsgBox(i.ToString & " " & "Messages Sent")
End Sub
Code:
Public Function GetEmailAdd()
If Table.Rows.Count <= 0 Then
MsgBox("There is No Data")
End If
Dim columnName = txttocol.Text
If Table.Columns.Contains(columnName) Then
Else
MsgBox("Column Name Not Found")
Return Nothing
End If
For Each row As DataRow In Table.Rows
If Not (row(columnName)) Is Nothing Then
emailadd.Add(row(columnName).ToString)
End If
Next
Return emailadd
End Function