VB: Email sending with SMTP is failing - vb.net

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.

Related

send data grid view data in an e-mail using vb.net

i'm trying to send a datagridview (or just the data in the grid) to an e-mail but i only receive a blank e-mail when it's sent, anyone got any ideas how to fix it?
The code im using is this:
Try
SMTP.UseDefaultCredentials = False
SMTP.Credentials = New Net.NetworkCredential("[e-mail address im sending from]", "[password for that e-mail]")
SMTP.Port = 25
SMTP.EnableSsl = True
mail = New MailMessage
mail.From = New MailAddress("[e-mail im sending from]")
mail.To.Add(UserEmail.Text)
mail.Body = DataTab.ToString
mail.Subject = "Biology quiz Highscores"
SMTP.DeliveryMethod = SmtpDeliveryMethod.Network
SMTP.Send(mail)
MsgBox("E-mail sent to: " & UserEmail.Text & "")
Catch ex As Exception
MsgBox("Unable to send e-mail. Please try again later.")
End Try
im getting the data from a 2003 access database using mydataadpter sql statement, the data table variable is called datatab.
Object.ToString(), unless overridden, is identical to calling Object.GetType().ToString().
You want to show the data in the data table. You could do something like this:
Private Sub YourSubWhereYouSendEmail()
'...
Try
Using smtp = New SmtpClient() With {
.UseDefaultCredentials = False,
.Credentials = New Net.NetworkCredential("[e-mail address im sending from]", "[password for that e-mail]"),
.Port = 25,
.EnableSsl = True,
.DeliveryMethod = SmtpDeliveryMethod.Network
}
smtp.Send(New MailMessage("[e-mail im sending from]"), UserEmail.Text, "Biology quiz Highscores", DataTableToCSVString(DataTab)))
End Using
MsgBox("E-mail sent to: " & UserEmail.Text & "")
Catch ex As Exception
MsgBox("Unable to send e-mail. Please try again later.")
End Try
'...
End Sub
Private Function DataTableToCSVString(table As DataTable) As String
With New Text.StringBuilder
Dim once = False
'headers
For Each col As DataColumn In table.Columns
If once = False Then
once = True
Else
.Append(",")
End If
.Append(col.ColumnName)
Next
.AppendLine()
'rows
For Each s In table.Select.Select(Function(row) String.Join(",", row.ItemArray))
.AppendLine(s)
Next
Return .ToString
End With
End Function

Email form: personalised 'thank you' page

I have this in a VB.NET contact form:
Protected Sub btnSubmit_Click1(sender As Object, e As EventArgs)
Dim mail As New MailMessage()
mail.To.Add(txtEmail.Text)
mail.From = New MailAddress("info#mySite.net")
mail.Subject = "Contact Form"
'mail.Bcc = New MailAddress
mail.Body = txtName.Text & vbCrLf & txtComments.Text
Dim smtp As New SmtpClient("mail.server")
smtp.Credentials = New NetworkCredential("EMAIL ID", "PWD")
smtp.Send(mail)
Response.Redirect("thankyou.aspx" & mail.To)
lblStatus.Text = "Your data has been submitted successfully"
txtName.Text = ""
txtEmail.Text = ""
txtComments.Text = ""
End Sub
The mail.To in Response.Redirect is giving me an error:
Operator '&' is not defined for types 'String' and 'System.Net.Mail.MailAddressCollection'.
I imagine I need to create a separate personalised aspx 'thank you' page, so I need a way of getting the user's name from the form field data.
Thanks for any advice.
Do you mean something like this:
Response.Redirect("thankyou.aspx" & Request.QueryString["email.Text"];
Mail.To is a collection. Try email.text (which is what you passed to the mail address).

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

System.Net.Mail VB.NET 3.5 System.Net.Mail.SmtpException

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.

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)