vb.net while sending smtp form get not responding - vb.net

I have this code:
For i = 0 To DataGridView1.RowCount - 2
If send_email(body, DataGridView1.Rows(i).Cells(8).Value.ToString) Then
countSentMail = countSentMail + 1
System.Threading.Thread.Sleep(2 * 1000)
ProgressBar1.PerformStep()
End If
Next i
Private Function send_email(ByVal body As String, ByVal emailAddress As String) As Boolean
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Port = [port]
SmtpServer.Host = [ip]
mail = New MailMessage()
mail.From = New MailAddress([email_from])
mail.To.Add([email_to])
mail.Bcc.Add([email_bbc])
mail.Subject = [subject]
mail.Body = body
Mail.IsBodyHtml = True
SmtpServer.Send(mail)
send_email = True
Catch ex As Exception
send_email = False
End Try
End Function
And when code runs form/application gets "not responding" till sends out all email and progress bar becomes useless. If I comment out content of sending function - progress bar works as I expect. Any suggestions?

Sorry for the delay on reply.
Yes. You are invoking send_email before increasing ProgressBar1
send_email uses SmtpClient.Send() which is synchronous and waits for a server response.
You can use SmtpClient.SendAsync() instead, which will continue the execution and waits the server response on background.

Related

VB.Net - Sending out mail as html and plaintext

I have a mail function 'Sendmail' in my VB app, as so...
Public Function Sendmail(ByVal mailrecipient As String, ByVal mailsubject As String, ByVal mailbody As String)
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New _
Net.NetworkCredential(internal_mail_server_username, internal_mail_server_password)
SmtpServer.Port = 25
SmtpServer.Host = internal_mail_server
mail = New MailMessage()
mail.From = New MailAddress(internal_email_sender)
mail.To.Add(mailrecipient)
mail.Subject = mailsubject
mail.IsBodyHtml = True
mail.Body = mailbody
SmtpServer.Send(mail)
MessageBox.Show("Mail successfully sent to " & mailrecipient)
Return "Success"
Catch ex As Exception
End Try
End If
End Function
This works great, passing the recipient, subject and body to it sends HTML mail out... fantastic.
What I need to is include with that email a plain text version with the mail that goes out.
Is there a simple way I can achieve this?
Use alterativeViews
'first create the Plain Text part
Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString(Plain_Text)
'then create the Html part
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(HTML_Text)
mail.AlternateViews.Add(plainView)
mail.AlternateViews.Add(htmlView)
Obviously you need to pass both the PLain_Text and HTML_Text as parameters to the routine.

can't send Email from Webservice written in vb.net

I wanna send an Email from my Webservice, written in vb.net, but I get an Timeout.
What is wrong?
Dim toaddress As MailAddress = New MailAddress("xxx")
Dim fromaddress As MailAddress = New MailAddress("yyy")
' The structure for MailMessage(from, to)
Dim message As MailMessage = New MailMessage(fromaddress, toaddress)
message.Subject = "I have sent you a message from a program!"
message.Body = "Hello World!"
Dim messanger As SmtpClient = New SmtpClient("smtpxxx", 995)
messanger.Credentials = New NetworkCredential("user", "password")
messanger.EnableSsl = True
messanger.Send(message)
You are doing many things wrong and some of the information you have given are not clear enough. host name and port names have to give properly. it chooses which mail service you are using, from your code it is not correctly provided, so i will give a snippet that uses gmail to send mail. please go through this and make changes as per your SmtpHost.
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("email", "password")
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress(txtemail.Text)
e_mail.To.Add(txtemail.Text)
e_mail.Subject = "Email Sending"
e_mail.IsBodyHtml = False
e_mail.Body = txtMessage.Text
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString)
End Try
This link help you to find the smtp.Server and Port numbers, you can use this thread for check the limitations of smtp.servers

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

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 send email to the user with all data input

I have two pages the first one will receive all data that are required from the user such as username e.mail and then the same page will do the calculation but when clicking on result button two things should happen: 1-the result and all user inputs should be sent to the second page 2- the same information should be sent to the user email as the e.mail messege
I wrote the e.mail code but I dont know how do put the results as message
Help please
This code worked for me
Try
Dim mail As MailMessage
Dim client As SmtpClient
Dim fromAddress As String
Dim toAddress As String
Dim subject As String
Dim message As String
fromAddress = "user#hotmail.com"
toAddress = "user#hotmail.com"
subject = "Radiation"
message = "mail sent"
mail = New MailMessage(fromAddress, toAddress, subject, message)
client = New SmtpClient("Smtp.live.com")
client.Port = 587
client.EnableSsl = True
client.UseDefaultCredentials = False
Dim SMTPUserInfo As New System.Net.NetworkCredential("user#hotmail.com", "password")
client.Credentials = SMTPUserInfo
client.Send(mail)
Label1.Text = "sent"
Catch ex As Exception
Label1.Text = ex.Message.ToString()
End Try