System.Net.Mail VB.NET 3.5 System.Net.Mail.SmtpException - vb.net

I have searched the net thoroughly for a solution to this and have yet to find one.
I'm trying to establish a simple mail client to send text documents as raw text through SMTP. To do this I am using the System.Net.Mail library under VB.Net version 3.5
Whenever I try to send a message, I receive a System.Net.Mail.SmtpException.
I have tried using different mail providers, under different settings and have yet to solve this problem. This problem has been tested on 3 separate computers, all with different specifications.
The code is as follows:
Private Sub SendEmailMessage()
Try
If My.Computer.Network.IsAvailable Then
If DataValid() Then
'Data is valid, send the eMail.
Dim MailReceiver As String = txtReceiver.Text
'Create the eMail Message.
'Dim message As New MailMessage(from:=txtMailAddress.Text, to:=MailReceiver, subject:="(MTG) <CARD> " & ID, body:="<p>" & ConstructedFileString() & "<p>")
Dim message As New MailMessage
Dim MessageFrom As New MailAddress(txtMailAddress.Text)
Dim MessageTo As New MailAddress(MailReceiver)
With message
.From = MessageFrom
.To.Add(MailReceiver)
.Subject = "(MTG) CARD " & ID
.IsBodyHtml = True
.Body = "<p>" & ConstructedFileString() & "<p>"
End With
'Establish eMail Client
Dim emailClient As New SmtpClient()
Dim emailCredentials As New Net.NetworkCredential
With emailCredentials
.UserName = txtMailAddress.Text
.Password = txtPassword.Text
.Domain = "gmail.com"
End With
With emailClient
.Host = txtHostServer.Text
.Port = txtPort.Text
.Credentials = emailCredentials
.EnableSsl = chkSSL.Checked
.Timeout = 5000
End With
'Dim MailDomain As String = ""
'Dim PositionAt As Byte = 0
'PositionAt = txtMailAddress.Text.IndexOf("#")
'For i = PositionAt + 1 To Len(txtMailAddress.Text)
' MailDomain = MailDomain & txtMailAddress.Text.Chars(i)
'Next
'Debug.Print(MailDomain)
If My.Computer.Network.Ping(hostNameOrAddress:=emailClient.Host) Then
'Send the message.
emailClient.Send(message)
Else
'Could not ping, do not send.
ErrorOut("Could not reach the eMail Server.")
End If
Else
'Data is not valid, do not send the eMail.
End If
Else
ErrorOut("No network could be found. Check your network configurations.")
End If
Catch ex As Security.SecurityException
'Security exception
ErrorOut("A Security Exception was raised.")
Catch ex As Net.NetworkInformation.NetworkInformationException
'Network info exception
ErrorOut("Exception raised when retrieving network information.")
Catch ex As Net.NetworkInformation.PingException
'Ping exception
ErrorOut("Exception raised when pinging the network.")
Catch ex As Net.Mail.SmtpFailedRecipientException
'Recipient exception
ErrorOut("Mail Recipient Exception raised.")
Catch ex As Net.Mail.SmtpException
'Mail Server Exception
ErrorOut("Mail Server Exception raised")
Catch ex As Exception
'Generic Exception raised.
ErrorOut("General Exception raised", True)
End Try
End Sub
Any help on this matter is greatly appreciated, thanks.
Stack trace:
System.Net.Mail.SmtpException: The operation has timed out.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at NetProj.EmailDialog.SendEmailMessage() in ...

I believe this is the famous SSL issue with System.Net.Mail
http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx
It was there in framework 3.5 not sure about 4.0 if they fixed it or not.

Related

VB: Email sending with SMTP is failing

I'm adding an email sender in my app, so i used this:
Try
Dim oMail As New SmtpMail("TryIt")
Dim oSmtp As New SmtpClient()
oMail.From = "app-NHK#hotmail.com" ' From
oMail.To = "NHKomaiha#hotmail.com" ' To
oMail.Subject = Title.Text 'Title
oMail.TextBody = MsgTxt.Text 'Body
Dim oServer As New SmtpServer("smtp.live.com") ' SMTP server address
oServer.User = "app-NHK#hotmail.com" 'here i have written my app's email address made for sending the email from this form
oServer.Password = "thepassword" 'here i have put my app email password
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto ' if SSL connection required
UseWaitCursor = True
Here done setting the main needed info
oSmtp.SendMail(oServer, oMail)
Sending...
UseWaitCursor = False
MessageBox.Show("E-Mail Sent Successfully", "Contact by E-Mail", MessageBoxButtons.OK, MessageBoxIcon.Information)
Main.BringToFront()
Main.Enabled = True
Close()
Error catching...
Catch ep As Exception
UseWaitCursor = False
MessageBox.Show("Error while sending E-Mail." & vbCrLf & vbCrLf & ep.Message, "Contact by E-Mail", MessageBoxButtons.OK, MessageBoxIcon.Error)
Dim closeerror = MessageBox.Show("Do you want to close?", "Contact by E-Mail", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If closeerror = DialogResult.Yes Then
Main.BringToFront()
Main.Enabled = True
Close()
End If
End Try
Is this code wrong? i used a lot of ways to send email but none worked
This time i got error: 550 5.3.4 Requested action not taken; To continue sending messages, please sign in to your account.
Modify and try this working example:
Imports System.Net.Mail
...
Try
Dim Email As New MailMessage()
Email.From = New MailAddress("abcdef#gmail.com")
Email.To.Add("other#provider.com")
Email.Subject = "Subject"
Email.IsBodyHtml = False 'or true if you want html
Email.Body = TextBox1.Text
Dim EmailClient As New SmtpClient("smtp.gmail.com", 587)
EmailClient.EnableSsl = True
EmailClient.Credentials = New Net.NetworkCredential("abcdef#gmail.com", "password")
EmailClient.Timeout = 7000
EmailClient.Send(Email)
Catch ex As SmtpException
MsgBox(ex.StatusCode & vbCrLf & ex.Message, vbCritical, "SMTP Error!")
End Try
Usually you need to specify port and authentication type in order to connect to an smtp server. It seems that smtp.live.com use SSL and port 465 (please verify this data).
So you can use SmtpClient.Port property to sets the port used for SMTP transactions and SmtpClient.EnableSSL to specify that SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.

What smtp do I use for email?

I have a basic vb.net windows form application and is wondering how I would go about sending an email? I have no servers set up or anything like that, I was wondering if I could still send it without setting up all that stuff. This is the code I have now:
Private Sub sendEmail(ByVal golfersTable As DataTable)
'create the mail message
Dim mail As New MailMessage()
Dim SMTP As New SmtpClient()
'set the addresses
mail.From = New MailAddress("someone#gmail.com")
mail.To.Add("someone#gmail.com")
'set the content
mail.Subject = "Golf Quotas"
mail.Body = "Golfer Name" & "-----------------------------------------------" & row.Item("Average Quota")
For Each row As DataRow In golfersTable.Rows
mail.Body = row.Item("Golfer Name") & "---------------" & row.Item("Average Quota")
Next
'set the server
SMTP.EnableSsl = True
SMTP.UseDefaultCredentials = False
SMTP.Port = "465"
'SMTP.Send(mail)
Try
SMTP.Send(mail)
MsgBox("Your Email has been sent sucessfully - Thank You")
Catch ex As Exception
MsgBox("Message Failed To Send" & ex.ToString)
End Try
End Sub
I have gotten nothing to work at all from everything that I have tried.... Idk what I'm doing wrong but it's not working. I tried a nslookup www.gmail.com in cammand prompt but it said that domain not found ?
If you are using a GMail account to send the emails then you can use Google's SMTP server, smtp.gmail.com.
More details here:
http://email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm

Check if SMTP is running or failed to send email

I am using SMTP server to send emails.
I would like to get an error message when the SMTP server is down or when the email was not delivered.
With DeliveryNotificationOptions.OnFailure I get an email that the email has not been delivered.
I would like to get an error. Is this possible?
How I can check if SMTP is running?
Here is the code I use:
Dim serverName As String = ""
Dim mailSenderInstance As SmtpClient = Nothing
Dim AnEmailMessage As New MailMessage
Dim sendersEmail As String = ""
Try
serverName = GetServerName("EMAIL_SERVER")
mailSenderInstance = New SmtpClient(serverName, 25)
sendersEmail = GetSendersEmail(msUserName)
AnEmailMessage.From = New MailAddress(sendersEmail)
'MAIL DETAILS
AnEmailMessage.Subject = "New Email"
AnEmailMessage.Body = "The Message"
AnEmailMessage.To.Add(anEmailAddress)
' Delivery notifications
AnEmailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
mailSenderInstance.UseDefaultCredentials = True 'False
mailSenderInstance.Send(AnEmailMessage)
Catch ex As System.Exception
MessageBox.Show(ex.ToString)
Finally
AnEmailMessage.Dispose()
mailSenderInstance.Dispose()
End Try
add another try catch block around your SMTP declaration
try
mailSenderInstance = New SmtpClient(serverName, 25)
catch ex as exception
msgbox( "Error creating SMTP connection: " & ex.message)
end try
regards
ok, you want to know the SMTP status. SMTP runs as a Service. I've written a function for you to know status of ANY service in the system. Add reference to "System.ServiceProcess" to your project.
''response: -1 = service missing, 0 = stopped or stopping, 1 = running
imports System.ServiceProcess ''add this at top
Private Function GetServiceStatus(ByVal svcName As String) As Integer
Dim retVal As Integer
Dim sc As New ServiceController(svcName)
Try
If sc.Status.Equals(ServiceControllerStatus.Stopped) Or sc.Status.Equals(ServiceControllerStatus.StopPending) Then
retVal = 0
Else
retVal = 1
End If
Catch ex As Exception
retVal = -1
End Try
Return retVal
End Function
use it like this:
'' use taskManager to figure correct service name
dim svStatus as integer = GetServiceStatus("SMTP")
if svStatus <> 1 then
msgbox("Service not running or absent")
else
''write your send mail code here
end if
hope this will help you

What is the usual way to check if internet connection exists and if SMTP mail is sent?

I'm sending emails through VB.NET like in showed code:
Dim retval As Integer
Dim attachment As System.Net.Mail.Attachment = Nothing
If fileName <> "" Then
attachment = New System.Net.Mail.Attachment(fileName)
End If
Dim client As New SmtpClient()
With client
.EnableSsl = True
.Host = smtpServerAddress
.Port = 587
.DeliveryMethod = SmtpDeliveryMethod.Network
.UseDefaultCredentials = False
.Credentials = New NetworkCredential(FromEmailId, password)
AddHandler .SendCompleted, AddressOf SendCompletedCallback
End With
Dim mail = New MailMessage(FromEmailId, toEmailId)
With mail
.Priority = MailPriority.High
.Subject = subject
.SubjectEncoding = System.Text.Encoding.UTF8
.IsBodyHtml = False
If fileName <> "" Then
.Attachments.Add(attachment)
End If
.Body = msgBody
.BodyEncoding = System.Text.Encoding.UTF8
End With
Try
client.SendAsync(mail, "")
retval = 1
Catch ex As Exception
retval = 0
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Return retval
This work's well.
Problem is only that my Try/Catch block dont react as expected if I'm not connected to internet. The only way I can know that mail didn't go out is that I don't receive message from callback what can take a long time. Also, I get returned 1 from function like email is sended properly.
Which is usual way to check if internet connection exists and if mail is start to be sended?
If you want to catch all exception thrown from SmtpClient you could send mail synchronously. If you prefer asynchronous way, use SendMailAsync which returns Task instance on which you can call ContinueWith to set error handler:
client.SendMailAsync(mail).ContinueWith(t=>HandleError(t.Exception), TaskContinuationOptions.OnlyOnFaulted)

how to check if a line of code actually succeeded?

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()
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
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.
You can use a bool method which always returns true or false of your sending status.
If you have no error then please check the emailId whether it exists or not.