Syntax error in 'New' - vb.net

I was coding sender of emails in vb.net and it is giving Syntax error. Code below:
Try
Dim message As New MailMessage With {
.Subject = Me.SubjectTxt.Text
}
message.To.Add(Me.ReceiverTxt.Text)
message.From = New MailAddress(Me.EmailTxt.Text)
message.Body = Me.BodyTxt.Text
Dim num2 As Integer = (Me.AttachmentListbox.Items.Count - 1)
Dim i As Integer = 0
Do While (i <= num2)
Dim item As New Attachment(Conversions.ToString(Me.AttachmentListbox.Items.Item(i)))
message.Attachments.Add(item)
i += 1
Loop
New SmtpClient(Me.ClientBox.Text) With { _
.EnableSsl = True, _
.Credentials = New NetworkCredential(Me.EmailTxt.Text, Me.PasswordTxt.Text), _
.Port = Conversions.ToInteger(Me.PortTxt.Text) _
}.Send(message)
Interaction.MsgBox(("Message sent to " & Me.ReceiverTxt.Text), MsgBoxStyle.Information, "SMTP Email Sender")
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim exception As Exception = exception1
If (Me.ReceiverTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Receiver.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.SubjectTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up Subject.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.BodyTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Message Body.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.EmailTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Email for Account Log In.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.PasswordTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Password for Account Log In.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.ClientBox.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Server for basis of SMTP Server.", MsgBoxStyle.Exclamation, "You missed something!")
ElseIf (Me.PortTxt.Text = Nothing) Then
Interaction.MsgBox("Please fill up the Port to successfully send the email.", MsgBoxStyle.Exclamation, "You missed something!")
Else
Interaction.MsgBox("Sending Failed", DirectCast(Conversions.ToInteger("SMTP Email Sender"), MsgBoxStyle), Nothing)
End If
ProjectData.ClearProjectError()
End Try
The error is in New SmtpClient

Problem of initializers - you don't know which line is a problem. First, break your code into many lines.
Dim smtp As New SmtpClient(Me.ClientBox.Text) With { .EnableSsl = True }
smtp.Credentials = New NetworkCredential(Me.EmailTxt.Text, Me.PasswordTxt.Text)
smtp.Port = Conversions.ToInteger(Me.PortTxt.Text)
smtp.Send(message)
Generally, your problem was in line starting with new. I just tested it, it doesn't work in vb. Something like this - (new class()).DoSomething works in c#. But not in vb. But then again, complex initializers can be detrimental in debugging issues. Now you will be able which line exactly causes the error.
Also, you should add .Trim() everywhere
Me.PortTxt.Text.Trim()

This should have worked:
With New SmtpClient(Me.ClientBox.Text.Trim) With {
.EnableSsl = True,
.Credentials = New NetworkCredential(Me.EmailTxt.Text.Trim, Me.PasswordTxt.Text.Trim),
.Port = Conversions.ToInteger(Me.PortTxt.Text.Trim) }
.Send(message)
End With
Note that the .Send is against the outer With block, and the underscores aren't needed. Also added .Trim as the other answer suggested.

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.

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

Download Direct links

My program has been using:
Dim DLLink1 As String
DLLink1 = Trim(TextBox2.Text)
Dim DownloadDirectory1 As String
DownloadDirectory1 = Trim(TextBox4.Text)
Try
Button3.Enabled = False
' My.Computer.Network.DownloadFile(DLLink1, (DownloadDirectory1 + "/UpdatedClient.zip"))
Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create(DLLink1), HttpWebRequest)
Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse)
Using Reader As New BinaryReader(HttpResponse.GetResponseStream())
Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10)
Using FStream As New FileStream(DownloadDirectory1 + "/UpdatedClient.zip", FileMode.Create)
FStream.Write(RdByte, 0, RdByte.Length)
End Using
End Using
End Using
Finally
MsgBox("Finished Download.")
Button3.Enabled = True
Label4.Visible = True
I tried this previously, and it didn't work at all:
My.Computer.Network.DownloadFile(DLLink1, (DownloadDirectory1 + "/UpdatedClient.zip"))
The website requires you to be logged in, so I made a spare account for the program:
WebBrowser1.Navigate("http://www.mpgh.net/forum/admincp/")
Timer1.Start()
Button2.Enabled = False
Then
WebBrowser1.Document.GetElementById("vb_login_username").SetAttribute("value", "AutoUpdaterAccount")
WebBrowser1.Document.GetElementById("vb_login_password").SetAttribute("value", "password")
Dim allelements As HtmlElementCollection = WebBrowser1.Document.All
For Each webpageelement As HtmlElement In allelements
If webpageelement.GetAttribute("type") = "submit" Then
webpageelement.InvokeMember("click")
Timer1.Stop()
Label5.Text = "Authorized."
Button2.Enabled = True
So now you're logged into the account, on the website, but when the code above to download runs, it downloads a zip, but it's corrupted. So I opened it with notepad++ and this is what I get (Does this mean it didn't login for the download, and it only logged in with the webbrowser and they aren't linked? Or something? Like My firefox logins aren't linked with chrome?:
The code is huge, it's like a HTML coding. Here is the link to a online notepad I put it on:
http://shrib.com/nCOucdfL
Another thing, a webbrowser can't be showing on the program, it can be on the outside not showing, like I did with the login. They also can't click the save button like on a normal web browser when a window pops up, I want it to download automatically to where they set it using a button which sets the directory as DownloadDirectory1
It must be your lucky day because today I woke up and decided that I would like to help you with your cause. I first tried to get the download to work with the web browser control but unfortunately I am sure this is not possible without extending the web browser control and we don't want to do that today.
As I mentioned in the comments, the only way I really know that this is possible (without user interaction) is to log in via the HttpWebRequest method. It's pretty tricky stuff. Definitely not for beginners.
Now I must admit that this isn't the cleanest, most "proper" and user-friendly code around, so if anyone wants to suggest a better way to do things, I am all ears.
I suggest you test this first before you incorporate it into your existing app. Just create a new vb.net app and replace all of the code in Form1 with the code below. You will have to update the usernamehere and passwordhere strings with your real username and password. Also, the file is saving to C:\file.rar by default so you can change this path if you want. This code completely removes the need for the web browser control (unless you are using it for something else) so most likely you can remove that from your real application once you incorporate this properly:
Imports System.Net
Imports System.IO
Imports System.Text
Public Class Form1
Private Const gsUserAgent As String = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
Const sUsername As String = "usernamehere"
Const sPassword As String = "passwordhere"
Const sMainURL As String = "http://www.mpgh.net/"
Const sCheckLoginURL As String = "http://www.mpgh.net/forum/login.php?do=login"
Const sDownloadURL As String = "http://www.mpgh.net/forum/attachment.php?attachmentid=266579&d=1417312178"
Const sCookieLoggedInMessage As String = "mpgh_imloggedin=yes"
Dim oCookieCollection As CookieCollection = Nothing
Dim sSaveFile As String = "c:\file.rar"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StartScrape()
End Sub
Private Sub StartScrape()
Try
Dim bContinue As Boolean = True
Dim sPostData(15) As String
sPostData(0) = UrlEncode("vb_login_username")
sPostData(1) = UrlEncode(sUsername)
sPostData(2) = UrlEncode("vb_login_password")
sPostData(3) = UrlEncode(sPassword)
sPostData(4) = UrlEncode("vb_login_password_hint")
sPostData(5) = UrlEncode("Password")
sPostData(6) = UrlEncode("s")
sPostData(7) = UrlEncode("")
sPostData(8) = UrlEncode("securitytoken")
sPostData(9) = UrlEncode("guest")
sPostData(10) = UrlEncode("do")
sPostData(11) = UrlEncode("login")
sPostData(12) = UrlEncode("vb_login_md5password")
sPostData(13) = UrlEncode("")
sPostData(14) = UrlEncode("vb_login_md5password_utf")
sPostData(15) = UrlEncode("")
If GetMethod(sMainURL) = True Then
If SetMethod(sCheckLoginURL, sPostData, sMainURL) = True Then
' Login successful
If DownloadMethod(sDownloadURL, sMainURL) = True Then
MessageBox.Show("File downloaded successfully")
Else
MessageBox.Show("Error downloading file")
End If
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Function GetMethod(ByVal sPage As String) As Boolean
Dim req As HttpWebRequest
Dim resp As HttpWebResponse
Dim stw As StreamReader
Dim bReturn As Boolean = True
Try
req = HttpWebRequest.Create(sPage)
req.Method = "GET"
req.AllowAutoRedirect = False
req.UserAgent = gsUserAgent
req.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
req.Headers.Add("Accept-Language", "en-us,en;q=0.5")
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
req.Headers.Add("Keep-Alive", "300")
req.KeepAlive = True
resp = req.GetResponse ' Get the response from the server
If req.HaveResponse Then
' Save the cookie info if applicable
SaveCookies(resp.Headers("Set-Cookie"))
resp = req.GetResponse ' Get the response from the server
stw = New StreamReader(resp.GetResponseStream)
stw.ReadToEnd() ' Read the response from the server, but we do not save it
Else
MessageBox.Show("No response received from host " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End If
Catch exc As WebException
MessageBox.Show("Network Error: " & exc.Message.ToString & " Status Code: " & exc.Status.ToString & " from " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function SetMethod(ByVal sPage As String, ByVal sPostData() As String, sReferer As String) As Boolean
Dim bReturn As Boolean = False
Dim req As HttpWebRequest
Dim resp As HttpWebResponse
Dim str As StreamWriter
Dim sPostDataValue As String = ""
Try
req = HttpWebRequest.Create(sPage)
req.Method = "POST"
req.UserAgent = gsUserAgent
req.Accept = "application/x-shockwave-flash,text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
req.Headers.Add("Accept-Language", "en-us,en;q=0.5")
req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
req.Referer = sReferer
req.ContentType = "application/x-www-form-urlencoded"
req.Headers.Add("Pragma", "no-cache")
req.Headers.Add("Keep-Alive", "300")
If oCookieCollection IsNot Nothing Then
' Pass cookie info from the login page
req.CookieContainer = SetCookieContainer(sPage)
End If
str = New StreamWriter(req.GetRequestStream)
If sPostData.Count Mod 2 = 0 Then
' There is an even number of post names and values
For i As Int32 = 0 To sPostData.Count - 1 Step 2
' Put the post data together into one string
sPostDataValue &= sPostData(i) & "=" & sPostData(i + 1) & "&"
Next i
sPostDataValue = sPostDataValue.Substring(0, sPostDataValue.Length - 1) ' This will remove the extra "&" at the end that was added from the for loop above
' Post the data to the server
str.Write(sPostDataValue)
str.Close()
' Get the response
resp = req.GetResponse
If req.HaveResponse Then
If resp.Headers("Set-Cookie").IndexOf(sCookieLoggedInMessage) > -1 Then
' Save the cookie info
SaveCookies(resp.Headers("Set-Cookie"))
bReturn = True
Else
MessageBox.Show("The email or password you entered are incorrect." & vbCrLf & vbCrLf & "Please try again.", "Unable to log in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
bReturn = False
End If
Else
' This should probably never happen.. but if it does, we give a message
MessageBox.Show("The email or password you entered are incorrect." & vbCrLf & vbCrLf & "Please try again.", "Unable to log in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
bReturn = False
End If
Else
' Did not specify the correct amount of parameters so we cannot continue
MessageBox.Show("POST error. Did not supply the correct amount of post data for " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End If
Catch ex As Exception
MessageBox.Show("POST error. " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function DownloadMethod(ByVal sPage As String, sReferer As String) As Boolean
Dim req As HttpWebRequest
Dim bReturn As Boolean = False
Try
req = HttpWebRequest.Create(sPage)
req.Method = "GET"
req.AllowAutoRedirect = False
req.UserAgent = gsUserAgent
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
req.Headers.Add("Accept-Language", "en-US,en;q=0.5")
req.Headers.Add("Accept-Encoding", "gzip, deflate")
req.Headers.Add("Keep-Alive", "300")
req.KeepAlive = True
If oCookieCollection IsNot Nothing Then
' Set cookie info so that we continue to be logged in
req.CookieContainer = SetCookieContainer(sPage)
End If
' Save file to disk
Using oResponse As System.Net.WebResponse = CType(req.GetResponse, System.Net.WebResponse)
Using responseStream As IO.Stream = oResponse.GetResponseStream
Using fs As New IO.FileStream(sSaveFile, FileMode.Create, FileAccess.Write)
Dim buffer(2047) As Byte
Dim read As Integer
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
oResponse.Close()
End Using
bReturn = True
Catch exc As WebException
MessageBox.Show("Network Error: " & exc.Message.ToString & " Status Code: " & exc.Status.ToString & " from " & sPage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
bReturn = False
End Try
Return bReturn
End Function
Private Function SetCookieContainer(sPage As String) As System.Net.CookieContainer
Dim oCookieContainerObject As New System.Net.CookieContainer
Dim oCookie As System.Net.Cookie
For c As Int32 = 0 To oCookieCollection.Count - 1
If IsDate(oCookieCollection(c).Value) = True Then
' Fix dates as they seem to cause errors/problems
oCookieCollection(c).Value = Format(CDate(oCookieCollection(c).Value), "dd-MMM-yyyy hh:mm:ss")
End If
oCookie = New System.Net.Cookie
oCookie.Name = oCookieCollection(c).Name
oCookie.Value = oCookieCollection(c).Value
oCookie.Domain = New Uri(sPage).Host
oCookie.Secure = False
oCookieContainerObject.Add(oCookie)
Next
Return oCookieContainerObject
End Function
Private Sub SaveCookies(sCookieString As String)
Dim sCookieStrings() As String = sCookieString.Trim.Replace(" HttpOnly,", "").Replace(" HttpOnly", "").Replace(" domain=.mpgh.net,", "").Split(";".ToCharArray())
oCookieCollection = New CookieCollection
For Each sCookie As String In sCookieStrings
If sCookie.Trim <> "" Then
Dim sName As String = sCookie.Trim().Split("=".ToCharArray())(0)
Dim sValue As String = sCookie.Trim().Split("=".ToCharArray())(1)
oCookieCollection.Add(New Cookie(sName, sValue))
End If
Next
End Sub
Private Function UrlEncode(ByRef URLText As String) As String
Dim AscCode As Integer
Dim EncText As String = ""
Dim bStr() As Byte = Encoding.ASCII.GetBytes(URLText)
Try
For i As Long = 0 To UBound(bStr)
AscCode = bStr(i)
Select Case AscCode
Case 48 To 57, 65 To 90, 97 To 122, 46, 95
EncText = EncText & Chr(AscCode)
Case 32
EncText = EncText & "+"
Case Else
If AscCode < 16 Then
EncText = EncText & "%0" & Hex(AscCode)
Else
EncText = EncText & "%" & Hex(AscCode)
End If
End Select
Next i
Erase bStr
Catch ex As WebException
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return EncText
End Function
End Class

Failure sending email

My test case is getting failed at assert.fail(), I am not having any clue what wrong it is going and where it is getting failed. Any idea to make this test case pass
Below is the test case
<Test()> _
Public Sub SendFtpFailureEmailShouldPassWithProcessingInfosAndSendEmail()
Dim em As EmailNotification = New EmailNotification()
Try
Dim pfis As ProcessingFileInfos = New ProcessingFileInfos(New FileInfo(AppSettingsReader.SchemaLocation), "Ftp")
Dim pfi1 As ProcessingFileInfo = New ProcessingFileInfo(New FileInfo("Test1.xml"))
pfi1.ContainsErrors = True
pfi1.Message = "File Failed"
pfi1.FileProcessStatus = "F"
pfi1.Channel = "Ftp"
pfis.Add(pfi1)
Dim pfi2 As ProcessingFileInfo = New ProcessingFileInfo(New FileInfo("Test2.xml"))
pfi2.ContainsErrors = True
pfi2.Message = "File Failed on Bad Data"
pfi2.FileProcessStatus = "F"
pfi2.Channel = "Ftp"
pfis.Add(pfi2)
Dim result As String = em.CreateFtpFailureEmail(pfis)
Assert.IsNotEmpty(result, "result is invalid")
Dim emailDetails As Email = New Email() With {.Body = result, _
.FromEmail = AppSettingsReader.TPLFromEmail, _
.FromEmailName = AppSettingsReader.TPLFromEmailName, _
.SmtpHost = AppSettingsReader.SmtpHost, _
.Subject = "FTP Failure Report", _
.ToEmail = "runu.ali#cdsglobal.co.uk"}
em.SendEmail(emailDetails)
Catch ex As Exception
Assert.Fail(ex.Message)
End Try
End Sub
sending mail code below:
Public Sub SendEmail(ByVal emailObj As Email)
Try
If emailObj Is Nothing Then
Throw New ArgumentNullException("emailObj", "emailObj cannot be null or empty")
End If
Dim em As New Net.Mail.MailMessage()
em.From = New MailAddress(emailObj.FromEmail, emailObj.FromEmailName)
em.To.Add(New MailAddress(emailObj.ToEmail))
em.Subject = emailObj.Subject
em.Body = emailObj.Body
em.IsBodyHtml = True
Dim SmTP As SmtpClient = New SmtpClient()
SmTP.Host = emailObj.SmtpHost
SmTP.Send(em)
Catch ex As SmtpException
Throw
Catch ex As FormatException
Throw
End Try
End Sub

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)