Getting Error while sending the email in .NET - vb.net

I have an application was working fine and all the email functionality was working fine.
From yesterday, I started getting below error
Error Message:Service not available, closing transmission channel. The server response was: 4.3.2 Service not available, closing transmission channel
My VB.net code for sendmail is given below:
Public Sub SendMessage(ByVal toAddress As String, ByVal ccAddress As String)
Try
Dim message As New MailMessage()
Dim client As New SmtpClient()
'Set the sender's address
message.From = New MailAddress(fromAddress)
If (toAddress.Trim.Length > 0) Then
For Each addr As String In toAddress.Split(";"c)
message.To.Add(New MailAddress(addr))
Next
End If
If (ccAddress.Trim.Length > 0) Then
For Each addr As String In ccAddress.Split(";"c)
message.CC.Add(New MailAddress(addr))
Next
End If
message.BodyEncoding = Encoding.UTF8
message.Subject = Subject
message.Body = Body
message.IsBodyHtml = True
client.Send(message)
Catch ex As Exception
ErrorHandler.WriteError(ex.Message)
End Try
End Sub
Please suggest what can be cause behind this error and do let me know how can I fix this issue.

There isn't anything wrong with your code. This part of the error message:
4.3.2 Service not available, closing transmission channel
Is actually coming from your mail server, and the framework is simply passing the error message on to your application, and throwing it as part of the exception.
4.x.x errors are usually temporary, and are meant to be retried. Typically mail servers are overloaded when they throw a 400 error.

Check your email and see if it starts working.
Instead of (or in addition to) smtp authentication, some email servers will allow mail to be sent for 30 minutes (or some length) after a client computer checks POP email. If this is the case, it can make an application that does not use smtp authentication appear work sometimes and not work sometimes, with no change in the code.

Related

vb.net WebClient.DownloadString fails with exception

I am working on a program in VS 2017 coding in VB.Net. The program downloads Web pages using Net.WebClient.DownloadString and then parses the data. It worked fine for a year or more then one day I started getting an exception when downloading the pages.
The ex.Message is: 'The underlying connection was closed: An unexpected error occurred on a send.'
The ex.InnerException.Message is: 'Unable to write data to the transport connection: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.'
I have VS 2017 installed on 2 other PC's at this location and on 1 at another location. They all continue to run the code without exception. It is only an issue on this PC.
The code is below (I changed the Web address but it fails for any valid URL).
Any ideas why this fails on my main PC only?
Public Function DownloadData() As Boolean
Dim strURL As String = "https://www.google.com/"
Dim strOutput As String
Try
Using WC As New Net.WebClient
strOutput = WC.DownloadString(strURL)
If strOutput.Length > 0 Then
If ParseData(strOutput) = True Then
Return True
End If
Else
Return False
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.InnerException.Message, "Error")
End Try
End Function

Email Function will not work properly in Visual Studios

I am trying to generate an email function where it sends the user an email, however for some reason it is just not working properly and it does not give any error messages.
It just brings up a message box stating that "There is a problem at this time. Please try again later". This is message box which appears when the email fails to be sent, however could you please help to resolve by issue.
Error Message says
It says that 'sends the email. SMTP.Send(email)- An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll Additional information: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at –
Please view the code below.
imports System.Net.Mail
Public Class EmailF
'assigns a new message to the email
Dim email As New MailMessage
'smtp is the server that has been used to send the email
Dim smtp As New SmtpClient
'assigns a new email address
Dim mail As System.Net.Mail.MailAddress
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
'selects which email address to send the email from...
email.From = New MailAddress("blood4all.business#gmail.com")
email.Subject = SubBox.Text
email.Body = MessBox.Text
email.To.Add(ToBox.Text)
'the smtp outlook host.
Dim SMTP As New SmtpClient("smtp.gmail.com")
'the smtp port.
SMTP.Port = 587
SMTP.EnableSsl = True
'the login details for the gmail account.
SMTP.Credentials = New System.Net.NetworkCredential("blood4all.business#gmail.com", "Blood123")
'starts the progress bar.
Timer1.Start()
ProgressB.Show()
'sends the email.
SMTP.Send(email)
'pop up box conirms that the email has been sent.
MsgBox("The e-mail has been sent!")
Catch ex As Exception
MsgBox("There is a problem at this time. Please try again later")
ProgressB.Hide()
End Try
End Sub
The exception message is :
An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll Additional information: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at ...
The credentials you pass are used only if you set the UseDefaultCredentials property to false before you set the new credentials. Otherwise your Windows credentials will be used.
Changing the value of this property clears the Credentials property, which is why you need to set it before passing the new credentials:
SMTP.UseDefaultCredentials = False
SMTP.Credentials = New System.Net.NetworkCredential("blood4all.business#gmail.com", "Blood123")
EDIT
You'll also have to "allow less secure applications" from your GMail account settings, as described in this SO question and the GMail support site. Normally, GMail requires applications to use either an application key.
SMTP (the protocol) doesn't have this functionality so you need to modify your account settings to allow connecting without an application key
I have now got this working as I created a new gmail account, maybe my all gmail account consisted of network and security issues which has now been amended. Thank for help and much appreciated.

Timeouts and Freezing in EWS with Office 365

I have a service that watches 2 email inboxes. One thread is created for each inbox. The new messages are read and marked as Read on startup, then the NewMail event handler handles all new mail after that.
We have been using EWS version 14. We had no issues retrieving emails.
After we moved the emails to Office 365, the problems started.
On startup, the retrieval and handling of existing new messages is still working fine.
After startup, when the NewMail event handler is triggered, the bind/load method times out, regardless of what we set the Timeout property to.
We tried to switch to the newest EWS version (15.0).
With the new version, the startup handling still works fine.
However, trying to bind one email in the NewMail event handler makes no error, but makes the inbox thread quit.
When there is a new email message in both inboxes, the entire service freezes on the Bind line (i let it sit for 40 minutes before having to kill the service).
We tried both EWS versions with the following, with no success:
The below code is used in the NewEmail event handler AND the startup processing of existing new messages. Why would the same code have issues in one place and not the other? How do i fix this?
I have also tried to use EmailMessage.Bind using the NotificationEventArgs object, but i have the same issues.
We tried a SyncLock to get around the lock up and/or timeout, but that did not help.
Thanks!
Private Sub HaveMail(ByVal sender As Object, ByVal e As Microsoft.Exchange.WebServices.Data.NotificationEventArgs)
Dim error_occured As Boolean = False
Try
Try
SyncLock lock
Logger.LogDebug("Just entered the Locked state of the HaveMail event")
Dim ir As FindItemsResults(Of Item) = service.FindItems(WellKnownFolderName.Inbox, New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False), New ItemView(20))
Do While ir.Items.Count > 0
For Each i As EmailMessage In ir
Try
Logger.LogDebug("About to load a newly received email message")
i.Load(PropertySet.FirstClassProperties)
Catch ex As Exception
Throw New Exception("Error while loading an email message: " & ex.Message)
End Try
Dim rm As New ReceivedMessage
rm.ReceivedDateTime = i.DateTimeReceived
rm.ToAddress = i.DisplayTo
rm.Subject = i.Subject
rm.Body = i.Body
rm.FromAddress = i.From.Address
Logger.LogDebug("Just loaded a newly received email message from " & rm.FromAddress)
Dim rme As New ReceivedMessageEvent
rme.msg = rm
RaiseEvent GotMail(Me, rme)
Logger.LogDebug("Just processed a newly received email message from " & rm.FromAddress)
i.IsRead = True
i.Update(ConflictResolutionMode.AlwaysOverwrite)
Next
ir = service.FindItems(WellKnownFolderName.Inbox, New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False), New ItemView(20))
Loop
End SyncLock
Generally speaking, it's not a good practice to do much of anything from within the actual event handler. So Update, FindItems, and Bind would all make a call back to EWS from within your handler, and that is not good. The ExchangeService object is also not thread safe. How did you get away with it before O365? I have no answer other than just lucky.
Thanks to an answer on my posting on MSN, I was able to fix the problem.
I needed to raise the DefaultConnectionLimit to 100. Apparently, it defaults to 2, which was not enough.

How do I check if an ftp server is online and get the error that it generates if it is not connected?

I am new to programming in vb.net. I have come a long ways in my development and understanding of vb, but there is one hurtle I can not seem to fix. I am hosting an ftp server on my pc and I am making an app for it to connect to my server and download files. The problem with all the sample code is that everyone ASSUMES the server WILL be ONLINE. My pc may not be running 24/7 and I also may not have the ftp service running.In the first case it shouldnt even register that it is connected. In the second case, it WILL say that is connected b/c the pc is on, but it will return that the machine ou are trying to connect to is actively refusing the connection. Is there a way to TRULY check if the program is indeed connected to the server WITHOUT generating a bunch of Exceptions in the debugger? All I want is a call like:
Dim ftponline As Boolean = False 'Set default to false
ftponline = checkftp()
If ftponline Then
'continue program
Else
'try a different server
End If
So it would be a function called checkftp that returns a boolean value of true or false.
Here is my info:
Using Visual Studio 2010 Pro
Using .Net framework 4
Can anyone help?
Thanks!
I have tried the rebex ftp pack as well as the Ultimate FTP Pack.
Here is the updated code:
Public Function CheckConnection(address As String) As Boolean
Dim logonServer As New System.Net.Sockets.TcpClient()
Try
logonServer.Connect(address, 21)
Catch generatedExceptionName As Exception
MessageBox.Show("Failed to connect to: " & address)
End Try
If logonServer.Connected Then
MessageBox.Show("Connected to: " & address)
Return True
logonServer.Close()
Else
Return False
End If
End Function
Public Sub ConnectFtp()
types.Clear()
models.Clear()
ListBox1.Items.Clear()
ListBox2.Items.Clear()
TextBox2.Clear()
Dim request As New Rebex.Net.Ftp
If CheckConnection(*) Then
Dim tempString As String()
request.Connect(*)
request.Login(*, *)
request.ChangeDirectory("/atc3/HD_Models")
Dim list As Array
list = request.GetNameList()
Dim item As String = ""
For Each item In list
tempString = item.Split(New Char() {" "c})
If types.Contains(tempString(0)) = False Then
types.Add(tempString(0))
End If
If models.Contains(item) = False Then
models.Add(item)
End If
Next
request.Disconnect()
request.Dispose()
ElseIf CheckConnection(*) Then
request.Connect(*)
request.Login(*, *)
request.ChangeDirectory(*)
Dim list2 As Array
list2 = request.GetNameList()
Dim item2 As String = ""
Dim tempString2 As String()
For Each item2 In list2
MessageBox.Show(item2)
tempString2 = item2.Split(New Char() {" "c})
If types.Contains(tempString2(0)) = False Then
types.Add(tempString2(0))
End If
If models.Contains(item2) = False Then
models.Add(item2)
End If
Next
request.Disconnect()
request.Dispose()
End If
End Sub
No matter what I do, the second server will not connect. I even put a messagebox to show what items were being returned in the second server, but there are no messageboxes apearing when I run the program with my server offline. Is there anyone who can help?
If your code is designed with proper exception catching, it shouldn't be generating a "bunch" of exceptions. The first exception you catch should be your indication that the connection failed and your code should cease attempting to communicate at that point. If for some reason you really need to check the connectivity before attempting the FTP connection, you should be able to simply attempt to synchronously open a TCP socket to the FTP server's port. If that works, it's up and running.
You could simply open a socket to the server's IP address on Port 21 (assuming default FTP port).
I'm not much of a VB.Net programmer, but here's a link to sample code:
http://vb.net-informations.com/communications/vb.net_Client_Socket.htm
If you can establish the socket connection, you know that something is listening on that port (though you have not yet proven it's an FTP server, or that it will accept your login credentials...).
If you wish to simply avoid exceptions in the debugger, you could place the connection code in a method and apply the DebuggerHidden attribute to that method.

VB IRC Client - writeStream only displays single word in IRC

Morning All,
I have been writing an ever so simple IRC client in visual basic. I have a niggly issue whereby when I am writing to the network stream. On other clients my message cuts off after the first space character. I'm sure this is something simple as the messages are being sent, receiving is fine and debugging the issue it wherever I read the message (i.e. if I debug.print the message being written to the stream it still includes all the words and spaces.) Here is my code.
Thanks in advance
'Send data to IRC Server
Sub Send(ByVal message)
Try
'Reformat message to IRC command
message = message & vbCrLf
Debug.Print(message)
'Convert message string into bytes
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(message)
'Write data to stream
ircStream.Write(sendBytes, 0, sendBytes.Length)
'Run test to see if the string sent matches the user input
Dim messageSent As String = Encoding.ASCII.GetString(sendBytes)
Debug.Print(messageSent)
'Display message on the screen( 0 = Sent Formatting )
PrintToScreen(message, 0)
Catch ex As Exception
'Catch error and display error message in the debug console
Debug.Print("Error Sending")
End Try
End Sub
You probably just need to prepend a ':' to your message like so...
PRIVMSG #chan_name :your message with spaces
By flushing, calling the flush function of the stream... Which (if I remember correctly) clears the data in the buffer, and writes it at the same time.
ircStream.Flush()