"Failure to send mail" Error [duplicate] - vb.net

I am making an SMTP mail application with C#.Net. It is working ok for Gmail settings, but I have to work it for a connection to VSNL. I am getting an exception: "Failure sending mail"
My settings seem perfect. What is the problem? Why am I getting the exception?
MailMessage mailMsg = new MailMessage();
MailAddress mailAddress = new MailAddress("mail#vsnl.net");
mailMsg.To.Add(textboxsecondry.Text);
mailMsg.From = mailAddress;
// Subject and Body
mailMsg.Subject = "Testing mail..";
mailMsg.Body = "connection testing..";
SmtpClient smtpClient = new SmtpClient("smtp.vsnl.net", 25);
var credentials = new System.Net.NetworkCredential("mail#vsnl.net", "password");
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
I am getting an exception following...
System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)

Check the InnerException of the exception, should tell you why it failed.

Try wrapping the Send call in a try catch block to help identify the underlying problem.
e.g.
try
{
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
Console.WriteLine(ex); //Should print stacktrace + details of inner exception
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}",ex.InnerException);
}
}
This information will help identify what the problem is...

Make sure your Anti Virus is blocking sending mails. In my case McAfee Access protection Rules were blocking sending mails, untick blocks and reports.

I used some but i am checking only this if send mail fails:
default value is false;
but it can't be change to true;
smtpClient.Port = smtpServerPort;
smtpClient.UseDefaultCredentials = false;
smtpClient.Timeout = 100000;
smtpClient.Credentials = new System.Net.NetworkCredential(mailerEmailAddress, mailerPassword);
smtpClient.EnableSsl = EnableSsl;
All function must be surround by a try catch;

Try by removing
smtpClient.EnableSsl = true;
I am not sure whether vsnl supports SSL and the port number you are using

Without seeing your code, it is difficult to find the reason for exception. Following are assumptions:
The serverHost of VSNL is smtp.vsnl.net
Exception:
Unable to read data from the transport connection: net_io_connectionclosed
Usually this exception occurs only when there is mismatch in username or password.

Check to see if the machine is being referred to by an IPv6 address. In my case using machine name gave me the same error. Using the ip4 address it did work (i.e. 10.0.0.4). I got rid of ipv6 and it started to work.
Not the solution i was looking for but given my limited understanding of ipv6 I did not know of other choices.

Related

Too many files open when using generic packager with external packager.xml file

I am using jpos 2.1.0 where i am using external packager xml file for iso8583 client. Due to large number of request in two or three days, i encountered "Too Many Files Open" and i have set ulimit -n = 50000. I doubt that the packager files are not been closed properly due to which this limit has been exceeded. Please help me to close the open file properly.
JposLogger logger = new JposLogger(isoLogLocation);
org.jpos.iso.ISOPackager customPackager = new GenericPackager(isoPackagerLocation+iso8583Properties.getPackager());
BaseChannel channel = new ASCIIChannel(iso8583Properties.getServerIp(), Integer.parseInt(iso8583Properties.getServerPort()), customPackager);
logger.jposlogconfig(channel);
try {
channel.setTimeout(45000);
channel.connect();
}catch(Exception ex) {
log4j.error(ex.getMessage());
throw new ConnectIpsException("Unable to establish connection with bank.");
}
log4j.info("Connection established using ASCIIChannel");
ISOMsg m = new ISOMsg();
m.set(0, "1200");
........
m.set(126, "connectIPS");
m.setPackager(customPackager);
log4j.info(ISOUtil.hexdump(m.pack()));
channel.send(m);
log4j.info("Message has been send");
ISOMsg r = channel.receive();
r.setPackager(customPackager);
log4j.info(ISOUtil.hexdump(r.pack()));
String actionCode = (String) r.getValue("39");
channel.disconnect();
return bancsxfr;
}
You know when you open a file, a socket, or a channel, you need to close it, right?
I don't see a finally in your try that would close the channel.
You have a huge leak there.

Adding events to Davical server using Http request and DDay.iCal

I am trying to add an event from my local database to the Davical server (in fact, this should apply to any CalDav server, as long as it is compliant with the CalDav protocol)...
From what I could read here, I can send a PUT request to add events contained in a VCALENDAR collection... So here is what I try to do:
try {
// Create the HttpWebRequest object
HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create("http://my_caldav_srv/davical.php/user/mycalendar");
// Add the network credentials to the request
Request.Credentials = new NetworkCredential(usr, pwd);
// Specify the method
Request.Method = "PUT";
// some headers - I MAY BE MISSING THINGS HERE???
Request.Headers.Add("Overwrite", "T");
// set the body of the request...
Request.ContentLength = bodyStr.Length;
Stream reqStream = Request.GetRequestStream();
// Write the string to the destination as a text file.
reqStream.Write( Encoding.UTF8.GetBytes(body), 0, body.Length);
// Set the content type header.
Request.ContentType = contentType.Trim();
// Send the method request and get the response from the server.
Response = (HttpWebResponse)Request.GetResponse();
}
catch (Exception e) {
throw new Exception("Caught error: " + e.Message, e);
}
The body I send is actually an emtpy calendar:
BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:PUBLISH
PRODID:-//davical.org//NONSGML AWL Calendar//EN
X-WR-CALNAME:My Calendar
END:VCALENDAR
For a reason I cannot understand, the call with "PUT" returns an error (405) Method Not Allowed. The PUSH returns (500) Internal Server Error, but looking at the debug details, the reason is the same as for the PUT case...
In debugging on the server side, I found out that the reason is that in caldav-PUT-vcalendar.php, the following clause is violated:
$c->readonly_webdav_collections
Well, first, let me mention that with the SAME credentials entered in Lightning, I am able to add/remove events and, on the admin interface, I actually made sure to grant ALL rights to the user. So I'd be surprised it is due to that...
Any help would be most appreciated !
Kind regards,
Nik
OK, I got it....
The reason is that one must put the event to some EVENT adress....
I.e. the "url" is not the collection's address, but the EVENT's address...
So the same code using the following address works:
string url="http://my_server/caldav.php/username/calendarpath/_my_event_id.ics";
Does anybody know if it is possible to insert / delete multiple events at once ???

Error 415 from IAV Rest API - Get verbose error message

I have been trying the Instant Account Verification using the REST api but have run into a couple issues. I receive an error 415(Problem Updating Account) when calling either the addTransferAccountForItem or addItemAndStartVerificationDataRequest api. I'm wondering if there is any way to get a more detailed error message to understand what I'm doing wrong when making these calls. The error message is being returned in XML format although it should be returned in JSON.
Here's an example snippet of how I'm making the addItemAndStartVerificationDataRequest call. GDURL is a simple class that holds the url and concatenates all parameters into a string in format "param1=param1Value&param2=param2Value...".
Any nudge in the right direction would be appreciated. Thank you.
The url I am using are:
addItemAndStartVerificationDataRequestURL=
baseUrl+jsonsdk/ExtendedInstantVerificationDataService/addItemAndStartVerificationDataRequest/
addTransferAccountForItem=
baseUrl+jsonsdk/TransferAccountManagement/addTransferAccountForItem/
logger.info("Attempting to add item and start verification");
try{
GDURL iavUrl = new GDURL(restURL + addItemAndStartVerificationDataRequestURL);
iavUrl.addParameter("cobSessionToken", cobrandSessionToken);
iavUrl.addParameter("userSessionToken", userSessionToken);
iavUrl.addParameter("contentServiceId", contentServiceId);
iavUrl.addParameter("accountNumber", accountNumber);
iavUrl.addParameter("routingNumber", routingNumber);
iavUrl.addParameter("credentialFields.enclosedType", "com.yodlee.common.FieldInfoSingle");
iavUrl.addParameter("credentialFields[0].displayName", "UserID");
iavUrl.addParameter("credentialFields[0].fieldType.typeName", "IF_LOGIN");
iavUrl.addParameter("credentialFields[0].helpText", "4710");
iavUrl.addParameter("credentialFields[0].isEditable", "true");
iavUrl.addParameter("credentialFields[0].maxlength", "32");
iavUrl.addParameter("credentialFields[0].name", "LOGIN");
iavUrl.addParameter("credentialFields[0].size", "20");
iavUrl.addParameter("credentialFields[0].value", bankUsername);
iavUrl.addParameter("credentialFields[0].valueIdentifier", "LOGIN");
iavUrl.addParameter("credentialFields[0].valueMask", "LOGIN_FIELD");
iavUrl.addParameter("credentialFields[1].displayName", "Password");
iavUrl.addParameter("credentialFields[1].fieldType.typeName", "IF_PASSWORD");
iavUrl.addParameter("credentialFields[1].helpText", "11976");
iavUrl.addParameter("credentialFields[1].isEditable", "true");
iavUrl.addParameter("credentialFields[1].maxlength", "40");
iavUrl.addParameter("credentialFields[1].name", "PASSWORD");
iavUrl.addParameter("credentialFields[1].size", "20");
iavUrl.addParameter("credentialFields[1].value", bankPassword);
iavUrl.addParameter("credentialFields[1].valueIdentifier", "PASSWORD");
iavUrl.addParameter("credentialFields[1].valueMask", "LOGIN_FIELD");
HttpURLConnection connection = null;
connection = (HttpURLConnection) iavUrl.getURL().openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
String s="";
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(iavUrl.getParamString());
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
while(bufferedReader.ready())
s+=bufferedReader.readLine()+"/n";
}
System.out.println("add item response: /n" + s);
}catch(IOException e){
logger.error("error occured", e);
}
The 415(problem updating account) is an error thrown by Yodlee's data agent when it encounters an exception while trying to aggregate the account from end site. This particular error is thrown for situations where the end site terminates the session established by the data agent as the user might have already been logged in to the end site directly.
To know more about error code please refer this document

What uri pattern do I need to communicate with my PC from my handheld device?

As I was reminded here, I need to probably use "ppp_peer" to programmatically connect from my Compact Framework app to my Web API app running on my PC.
I have tried this (replacing an IPAddress with "ppp_peer"):
string uri = string.Format("http://ppp_peer:28642/api/FileTransfer/GetHHSetupUpdate?serialNum={0}&clientVersion={1}", serNum, clientVer);
...but I get, "NullReferenceException" in "Main" (prior to this I got "Unable to Connect to the Remote Server").
I have a breakpoint in the server code, but it doesn't reach that, so it must be somewhere in the client where this is occurring.
The client code in context is:
string uri = string.Format("http://ppp_peer:28642/api/FileTransfer/GetHHSetupUpdate?serialNum={0}&clientVersion={1}", serNum, clientVer);
RESTfulMethods.DownloadNewerVersionOfHHSetup(uri);
. . .
public static void DownloadNewerVersionOfHHSetup(string uri)
{
string dateElements = DateTime.Now.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);
var outputFileName = string.Format("HHSetup_{0}.exe", dateElements);
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
string statusCode = webResponse.StatusCode.ToString();
if (statusCode == "NoContent")
{
MessageBox.Show("You already have the newest available version.");
}
else
{
var responseStream = webResponse.GetResponseStream();
using (Stream file = File.Create(outputFileName))
{
CopyStream(responseStream, file);
MessageBox.Show(string.Format("New version downloaded to {0}", outputFileName));
}
}
}
catch (WebException webex)
{
string msg = webex.Message;
string innerEx = webex.InnerException.ToString();
string status = webex.Status.ToString();
MessageBox.Show(string.Format("Message: {0}; Status: {1}; inner Ex: {2}", msg, status, innerEx));
}
}
Do I need an IPAddress in addition to ppp_peer, or is my formatting of the URI wrong, or...???
UPDATE
After the "NRE" I also see, ""...encountered a serious error and must shut down"
I changed the code from above to see just what ppp_peer is translated as:
IPAddress ipAd = Dns.Resolve("PPP_PEER").AddressList[0];
string IPAddr = ipAd.ToString();
MessageBox.Show(IPAddr);
string uri = string.Format("http://{0}:28642/api/FileTransfer/GetHHSetupUpdate?serialNum={1}&clientVersion={2}", IPAddr, serNum, clientVer);
The MessageBox call shows me "192.168.55.100" which is different from what I thought my PC's IPAddress was...???
I get the same with:
IPAddress ipAd = Dns.GetHostEntry("PPP_PEER").AddressList[0];
UPDATE 2
Using this instead (I got it from here [Get ip address of host pc from windows mobile when connected via ActiveSync):
IPAddress ipAd = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
...the IP Address displayed is "one up" (192.168.55.101), and instead of an NRE, I get:
Message: Unable to connect to the remote server; Status: ConnectFailure; inner Ex: System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it at System.Net.Sockets.SocketConnectNoCheck(EndPoint remoteEP) ...
So it seems I'm doing all I can on the client end, and the server hears the knock, but is not opening the door - am I right?
BTW, out of curiosity I also added this code:
string hostName = Dns.GetHostName();
MessageBox.Show(string.Format("host name is {0}", hostName));
...and I see "WindowsCE"
UPDATE 3
According to this post by Andy Wiggly (the cat/bloke who wrote "MS .NET Compact Framework"), you do use "ppp_peer":
HttpWebRequest request = REST.CreateRequest(#"http://ppp_peer/DataServicesWebsite/NorthwindService.svc/Customers",
HttpMethods.GET, String.Empty, #"application/atom+xml", "", "");
The interestingest thing about this is the lack of a port assignment (":28642" or whatever); however, this style also gives me an NRE (yes, kind of like a Null Ready to Eat).
UPDATE 4
So what uri will it take to access the host machine from the handheld device?
I have tried all of the following permutations from the client/Compact Framework app, and none work:
IPAddress ipAd = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
string IPAddr = ipAd.ToString();
//string uri = string.Format("http://ppp_peer/api/...
//string uri = string.Format("http://ppp_peer:28642/api...
//string uri = string.Format("http://PPP_PEER/api/...
string uri = string.Format("http://PPP_PEER:28642/api/...
//string uri = string.Format("http://{0}:28642/api/...
//string uri = string.Format("http://192.168.125.50:28642/api/...
//string uri = string.Format("http://Platypus:28642/api/...
RESTfulMethods.DownloadNewerVersionOfHHSetup(uri);
The error is happening somewhere in that client code (can't step through it, so I don't know exactly where), because I have a breakpoint on the last line shown, and it is never reached.
SERVER (Web API) code:
[Route("api/FileTransfer/GetUpdatedHHSetup")]
public HttpResponseMessage GetUpdate(string serialNum, string clientVersion)
{
return _fileTransfer.GetHHSetupUpdate(serialNum, clientVersion);
}
public HttpResponseMessage GetHHSetupUpdate(string serialNum, string clientVersion)
{
HttpResponseMessage result;
string filePath = GetAvailableUpdateForCustomer(serialNum); // <= breakpoint on this
line
I put some debug lines in DownloadNewerVersionOfHHSetup() so that it now looks like this:
public static void DownloadNewerVersionOfHHSetup(string uri)
{
MessageBox.Show("Made it into DownloadNewerVersionOfHHSetup");
string dateElements = DateTime.Now.ToString("yyyyMMddHHmmssfff",
CultureInfo.InvariantCulture);
var outputFileName = string.Format("HHSetup_{0}.exe", dateElements);
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
MessageBox.Show("Made it into DownloadNewerVersionOfHHSetup #2");
var webResponse = (HttpWebResponse)webRequest.GetResponse();
MessageBox.Show("Made it into DownloadNewerVersionOfHHSetup #3");
. . .
I never see "#3", so it must be a problem inside the call to GetResponse(), but how can I find out exactly what? I get the NRE, then "...encountered a serious error and must shut down"
This is where it tries to call the server but, as mentioned, it never makes it to the server method being called...
UPDATE 5
It turns out that this now works:
http://192.168.125.50:28642/api/
...and the main reason that it does is because there was a mismatch between my routing attribute (GetUpdatedHHSetup) and what I was calling from the client (GetHHSetupUpdate). Once I aligned those planets, the NRE went away, and I got the expected result.
PPP_PEER is not needed in the uri/connection string. Using the host PC's IP Address (and port number for the server/Web API app) works now (after fixing the mismatch between the routing attribute and what the client was calling it).
I reckon using the machine name would work just as well, too.

Google Spellcheck

I'm unable to access the Google spell check service located at this address:
https://www.google.com/tbproxy/spell
is anyone else having this problem? I keep getting "bad gateway" when I try to connect. I'm pretty sure the service is offline.
Is there any news on what's going on? I know Google Drive went down a few weeks ago with the same set of error messages.
You can try this below Java code. This doesn't require any API Key. But please note, if you run it frequently, it will stop working as google blocks the IP Address from making future calls. You can use it on small data set. Not ideal solution, but if it is part of some batch job which runs in a while, then this approach may be acceptable to you.
public static String getSpellCheckedText(String Text) throws Exception {
String google = "http://www.google.com/complete/search?output=toolbar&q=";
String search = Text;
String charset = "UTF-8";
String spellCheckedText = Text;
URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
BufferedReader bufReader = new BufferedReader(reader);
String line = bufReader.readLine();
StringBuffer sBuffer = new StringBuffer();
while (line != null) {
sBuffer.append(line).append("\n");
line = bufReader.readLine();
}
String content = sBuffer.toString();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(content));
Document document = builder.parse(is);
NodeList nodeList = document.getElementsByTagName("suggestion");
if (nodeList != null && nodeList.getLength() > 0) {
org.w3c.dom.Node elm = nodeList.item(0);
if (elm.getNodeType() == Node.ELEMENT_NODE) {
Element suggestionElement = (Element)elm;
String suggestedString = suggestionElement.getAttribute("data");
if (suggestedString != null && suggestedString.trim().length() != 0) {
spellCheckedText = suggestedString.trim();
System.out.println(Text + " => "+ spellCheckedText);
}
}
}
return spellCheckedText;
}
I am also having this problem. I am getting a 503 Server Error. The problem is definitely on Google's end. (N.B. I am on Safari 6.0.3)
In specific...
503. That's an error.
The service you requested is not available at this time.
Service error -27. That’s all we know.
It seems as though Google is having some problems with their services. Hopefully they fix it soon!
Ditto, here. I really depend on it to check spelling in text boxes. It says "Unable to connect to Google spelling servers. Please check your internet connection and try again"