Quote:
|
Is there a way to catch the error and get the user to put in a real email address?
|
Yes, there is. But rather than provide you with the full answer, I'll show you how you find the answer yourself. That way, when other types of exceptions are thrown you know how to find those as well. As there are many, many different Exception types in .NET, understanding when the occur is very useful for other situations, not related to e-mail. Try this:
1. Create a brand new ASPX page
2. In the Code Behind, add this:
Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
Dim myMessage As New MailMessage()
myMessage.Subject = "Test"
myMessage.From = New MailAddress("[email protected]")
myMessage.To.Add(New MailAddress("[email protected]"))
Dim myClient As New SmtpClient()
Try
myClient.Send(myMessage)
Catch ex As Exception
End Try
End Sub
3. Put a break point on the line that starts with Catch and hit F5.
4. The code will crash (as the e-mail address is not valid) and the Catch line will be highlighted
5. Put a Watch on the ex variable and expand it in the Watch window. On the first line you'll see from what Exception type it derives.
6. Modify the code as follows:
Code:
Dim myMessage As New MailMessage()
myMessage.Subject = "Test"
myMessage.From = New MailAddress("[email protected]")
myMessage.To.Add(New MailAddress("[email protected]"))
Dim myClient As New SmtpClient()
Try
myClient.Send(myMessage)
Catch someException As TheTypeOfExceptionYouFoundInStep5
myMessage.From = New MailAddress("[email protected]")
myClient.Send(myMessage)
Catch ex As Exception
' Unknow exception
End Try
Don't forget to change the type of exception in the first Catch block and change
[email protected] to a valid e-mail address.
Now, when you send the message and the exception occurs, the first Catch block with your exception type is hit. Inside that block you can change the To address and try to send the message again. Other exceptions that may occur in the Try block are caught by the general Catch block.
Hope this helps.
Cheers,
Imar