views:

71

answers:

3

I'm making an email sending program and still I don't know how to check if the mail was really sent or not, because sometimes the program will have no error messages but the mail was not actually sent. Is there any other way on how to deal with this except for making use of try catch?

Here is my code:

Try
  mail.From = New MailAddress(TextBox2.Text)
  mail.To.Add(New MailAddress(TextBox1.Text))
  mail.Subject = TextBox4.Text
  mail.Body = TextBox4.Text
  mail.IsBodyHtml = True
  Dim client As SmtpClient = New SmtpClient("smtp.gmail.com", 587)
  If TextBox2.Text.Contains("@gmail.com") Then
    client.EnableSsl = True
    client.Credentials = New System.Net.NetworkCredential(TextBox2.Text, TextBox3.Text)
    Try
      client.Send(mail)
    Catch ex As Exception
      MessageBox.Show("Sending email failed. Please Try again")
    End Try
  End If
Catch
  MsgBox("Please input the correct value!")
End Try
ProgressBar1.Value = 100
clear()
A: 

Hai,

You can use a bool method which always returns true or false of your sending status..

If you have no error then plz check the emailId whether it exists or not...

Pandiya Chendur
A: 

I would typically use try/catch for this sort of thing.

Instead of catching a Generic Exception you can catch SmtpException and SmtpFailedRecipientsException's.

SmtpException is thrown when a connection could not be made or operation timed out. SmtpFailedRecipientsException is thrown if The message could not be delivered to one or more of the recipients.

Converted MSDN Code

Try
    client.Send(message)
Catch ex As SmtpFailedRecipientsException
    For i As Integer = 0 To ex.InnerExceptions.Length - 1
        Dim status As SmtpStatusCode = ex.InnerExceptions(i).StatusCode
        If status = SmtpStatusCode.MailboxBusy OrElse status = SmtpStatusCode.MailboxUnavailable Then
            Console.WriteLine("Delivery failed - retrying in 5 seconds.")
            System.Threading.Thread.Sleep(5000)
            client.Send(message)
        Else
            Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions(i).FailedRecipient)
       End If
    Next
Catch ex As Exception
    Console.WriteLine("Exception caught in RetryIfBusy(): {0}", ex.ToString())
End Try
Elijah Glover
A: 

Another problem you may run into is that the mail is being sent but it is not getting there due to spam filtering. If it works to one email address it should work for all ignoring the TextBox2 check for gmail address.

Jeff Beck