Operation timed out error - c#

I am hitting a wall with reCaptcha.net
Some background -
I am using reCaptcha-dotnet v1.0.5 which I got from http://code.google.com/p/recaptcha/downloads/list?q=label:aspnetlib-Latest.
I was able to develop a site and make it work locally with reCaptcha validation. When I deploy it to the server (the site is hosted on 1and1.com), I am getting the error below -
The operation has timed out
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The operation has timed
out
I have checked the google forums which advise to have the server allow outbound connections from Port 80. I tried to explain this to the support guy at 1and1.com but I don't think he has a clue at all.
Other than the above, is there anything I could do code-wise to resolve this? Has anybody figured a solution for this?
Appreciate any kind of advise!

This is the code I use for mail configuration and Recaptcha proxy for a web site that is hosted on 1and1 :
1- Web.config (only works if put there !)
<system.net>
<mailSettings>
<smtp from="mail#domain.com">
<network host="smtp.1and1.com" port="25" userName="mymail#domain.com" password="mypassword"/>
</smtp>
</mailSettings>
<defaultProxy>
<proxy usesystemdefault = "false" bypassonlocal="false" proxyaddress="http://ntproxyus.lxa.perfora.net:3128" />
</defaultProxy>
</system.net>
2- Inside a dedicated action in mycontroller :
// ouside the action I've defined the response
private class gapi {public bool success{get;set;}}
public bool SendMail(string firstname, string lastname, string email, string message, string grecaptcha)
{
SmtpClient smtp = new SmtpClient("smtp.1and1.com");
MailMessage mail = new MailMessage();
mail.From = new MailAddress(email);
mail.To.Add("mail#domain.com");
mail.Subject = firstname + " " + lastname;
mail.Body = message;
try
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["secret"] = "6LcEnQYTAAAAAOWzB44-m0Ug9j4yem9XE4ARERUR";
values["response"] = grecaptcha;
values["remoteip"] = Request.UserHostAddress;
var response = client.UploadValues("https://www.google.com/recaptcha/api/siteverify","POST", values);
bool result = Newtonsoft.Json.JsonConvert.DeserializeObject<gapi>((Encoding.Default.GetString(response) as string)).success;
if(!result) return "Something is wrong)";
}
//... verify that the other fields are ok and send your mail :)
smtp.Send(mail);
}
catch (Exception e) { return "Something is wrong)"; }
return "Okey :)";
}
Hope this helps.

Finally got the solution, I got the correct proxy server address from 1and1 and used that. reCaptcha works great now.
Also, for some reason, setting the proxy value in the code using the IWebProxy property of the reCaptcha control did not work. I had to add the tag in web.config under .

Related

Sending email via Gmail SMTP hangs indefinitely without error

In my ASP.NET MVC 5 application, I use emails (System.Net.Mail) primarily for account authentication. It's worked perfectly until recently, and I have no idea what happened. I didn't change anything even slightly related to emails, as far as I know.
When I try to step into the SendAsync call in the controller, it transfers control back to the browser where it hangs indefinitely. Eventually I have to stop and restart the application pool just to access any page, which takes a couple minutes (usually it can be turned back on almost instantly).
I have it set up to use a Google app password, which is a requirement (you get an error about security otherwise). It doesn't seem to even get as far as Google, since the new app password hasn't been used.
I've tried the TLS port as well as the SSL port. Last time I got it working was using TLS.
Web.config:
<configuration>
<appSettings>
<add key="SmtpUsername" value="email#gmail.com" />
<add key="SmtpPassword" value="AppPassword" />
<add key="SmtpSender" value="email#gmail.com" />
<add key="SmtpHost" value="smtp.gmail.com" />
<add key="SmtpPort" value="587" /> <!-- SSL: 465, TLS: 587 -->
<add key="SmtpEnableSsl" value="true" />
</appSettings>
</configuration>
Email code:
public class EmailClient : SmtpClient
{
public EmailClient()
{
UseDefaultCredentials = false;
Host = WebConfigurationManager.AppSettings.Get("SmtpHost");
Port = int.Parse(WebConfigurationManager.AppSettings.Get("SmtpPort"));
EnableSsl = bool.Parse(WebConfigurationManager.AppSettings.Get("SmtpEnableSsl"));
Credentials = new NetworkCredential(WebConfigurationManager.AppSettings.Get("SmtpUsername"),
WebConfigurationManager.AppSettings.Get("SmtpPassword"));
DeliveryMethod = SmtpDeliveryMethod.Network;
Timeout = 30000; // Waiting 30 seconds doesn't even end the "loading" status
}
}
public class EmailMessage : MailMessage
{
private bool isBodyHtml = true;
public EmailMessage(string subject, string body, string recipients)
: base(WebConfigurationManager.AppSettings.Get("SmtpSender"), recipients, subject, body)
{
IsBodyHtml = isBodyHtml;
}
public EmailMessage(string subject, string body, IEnumerable<string> recipients)
: base(WebConfigurationManager.AppSettings.Get("SmtpSender"), string.Join(",", recipients), subject, body)
{
IsBodyHtml = isBodyHtml;
}
}
public static class Email
{
/// <param name="recipients">Comma-delimited list of email addresses</param>
public static async Task SendAsync(string subject, string body, string recipients)
{
using (EmailMessage msg = new EmailMessage(subject, body, recipients))
using (EmailClient client = new EmailClient())
{
await client.SendMailAsync(msg);
}
}
/// <param name="recipients">Collection of email addresses</param>
public static async Task SendAsync(string subject, string body, IEnumerable<string> recipients)
{
using (EmailMessage msg = new EmailMessage(subject, body, recipients))
using (EmailClient client = new EmailClient())
{
await client.SendMailAsync(msg);
}
}
}
Usage:
public class TestController : BaseController
{
public async Task<ActionResult> Test()
{
await Email.SendAsync("TEST", "test", "anaddress#gmail.com");
return View(); // Never reaches this point
}
}
OP here. As some answers allude, there was nothing wrong with my code. I'm not sure which of the below I had changed without retesting, but this is what you must have to use Gmail SMTP:
Use TLS port 587
Set SmtpClient.EnableSsl to true
Enable MFA for the Google account and use an app password for the SmtpClient.Credentials. I needed to enable MFA to create an app password.
Please note the Documentation and see the Gmail sending limits. under Gmail SMTP server section.
Your code looks fine, the only thing I see is that you are enabling SSL, but using the port distained for 'TLS' so users who will use the SSL method, will engage in an issue.
Beside from that, nothing appears to the eye.
There is standard way to send emails from ASP.NET.
web.config
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" password="password" port="587" userName="user#gmail.com"/>
</smtp>
</mailSettings>
</system.net>
.cs
var smtp = new SmtpClient(); // no other code.
var msg = CreateEmailMessage();
//I use try... catch
try{
smtp.Send(msg);
//return true; //if it is a separate function
}
catch(Exception ex){
//return false;
//use ex.Message (or deeper) to send extra information
}
Note that Gmail doesn't except a sender other than username. If you want your addressee to answer to another address then use
msg.ReplyToList.Add(new MailAddress(email, publicName));

SendGrid Tutorial resulting in Bad Request

I apologize if this is a dupe question, but I have not found any solid information about this issue either on this site or on others.
With that being said, I am working on an MVC 5 web application. I am following this tutorial over on ASP.net.
public async Task SendAsync(IdentityMessage message)
{
await configSendGridasync(message);
}
private async Task configSendGridasync(IdentityMessage message)
{
var myMessage = new SendGridMessage();
myMessage.AddTo(message.Destination);
myMessage.From = new System.Net.Mail.MailAddress(
"info#ycc.com", "Your Contractor Connection");
myMessage.Subject = message.Subject;
myMessage.Text = message.Body;
myMessage.Html = message.Body;
var credentials = new NetworkCredential(
Properties.Resources.SendGridUser,
Properties.Resources.SendGridPassword,
Properties.Resources.SendGridURL // necessary?
);
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
if (transportWeb != null)
{
await transportWeb.DeliverAsync(myMessage);
}
else
{
Trace.TraceError("Failed to create Web transport.");
await Task.FromResult(0);
}
}
Each time it gets to the await transportWeb.SendAsync(myMessage) line in the above method, this error shows up in the browser:
Server Error in '/' Application.
Bad Request
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Exception: Bad Request
Line 54: if (transportWeb != null)
Line 55: {
Line 56: await transportWeb.DeliverAsync(myMessage);
Line 57: }
Line 58: else
Line 59: {
Line 60: Trace.TraceError("Failed to create Web transport.");
Line 61: await Task.FromResult(0);
Line 62: }
I signed up for a free account over at https://sendgrid.com/, using the "Free Package Google", giving me 25,000 monthly credits. The account has been provisioned.
I have tried a bunch of things so far including: disabling SSL, putting username/password directly in the code instead of pulling them from the Resources.resx file, specifying the SMTP server inside the NetworkCredential object, and also tried changing DeliverAsync(...) to Deliver().
I tried explicitly setting the subject instead of using message.Subject, as this post suggested. I also tried HttpUtility.UrlEncode on the callbackUrl generated in the Account/Register method as suggested here. Same results, unfortunately.
Does anyone happen to have some insight as to what might be causing this to not function correctly?
I ended up using the built-in SmtpClient to get this working. Here is the code that I am using:
private async Task configSendGridasync(IdentityMessage message)
{
var smtp = new SmtpClient(Properties.Resources.SendGridURL,587);
var creds = new NetworkCredential(Properties.Resources.SendGridUser, Properties.Resources.SendGridPassword);
smtp.UseDefaultCredentials = false;
smtp.Credentials = creds;
smtp.EnableSsl = false;
var to = new MailAddress(message.Destination);
var from = new MailAddress("info#ycc.com", "Your Contractor Connection");
var msg = new MailMessage();
msg.To.Add(to);
msg.From = from;
msg.IsBodyHtml = true;
msg.Subject = message.Subject;
msg.Body = message.Body;
await smtp.SendMailAsync(msg);
}
Even though it doesn't use SendGrid's C# API, the messages still show up on my SendGrid dashboard.
It might be a problem with your credentials.
If you signed up with SendGrid through Windows Azure, then you need to do the following:
Log in to your Azure Portal
Navigate to the Marketplace
Locate and click on the SendGrid application
Down at the bottom, click on Connection Info
Use the Username and Password listed.
I was initially under the impression that I was to use my Azure account password until I found this. Hope this corrects your problem like it did for me.
Check that you are using the correct "username" as the "mailAccount" setting.
This should be your sendgrid username, NOT the email address of the account you are trying to send from.
I had created an SendGrid account via Azure,
I fixed this by setting these values in my Web.Config file:
<add key="mailAccount" value="azure_************#azure.com" />
<add key="mailPassword" value="[My Azure Password]" />
to my azure username and password. the username I found from the Azure Dashboard, I navigated to SendGrid Accounts >> [Clicked the Resource I had Created] >> Configurations. The password was the same one I set up the Azure account with.
I also faced this issue. solved by adding textcontent and htmlcontent. Before i was sending empty string.now its working
code below
var client = new SendGridClient(_apiKey);
var from = new EmailAddress(_fromEmailAddress, _fromName);
var to = new EmailAddress("devanathan.s#somedomain.com", "dev");
var textcontent = "This is to test the mail functionality";
var htmlcontent = "<div>Devanathan Testing mail</div>";
var subject = "testing by sending mail";
var msg = MailHelper.CreateSingleEmail(from, to, subject, textcontent, htmlcontent);
var response = await client.SendEmailAsync(msg);
I got the same error. All I had to do was to copy the appsettings in webconfig(see below) and paste it into the OTHER webconfig file (there are 2 of them in asp.net project).
<add key="webpages:Version" value="3.0.0.0" />
<add key="mailAccount" value="xxUsernamexx" />
<add key="mailPassword" value="Password" />
I had the same problem and the problem was that I had the same email on TO and BCC field. Hope it helps others..
I had the same problem, happened to have misspelled the name of the config value for the mailAccount (put mainAccount instead of the mailAccount).
NetworkCredential credential = new NetworkCredential(ConfigurationManager.AppSettings["mailAccount"], ConfigurationManager.AppSettings["mailPassword"]);
Web transportWeb = new Web(credential);
The config value was coming back as null but the exception wasnt raised and the empty username was assigned instead. Basically, put the breakpoint on the line "Web transportWeb = new Web(credential);" and see what username/password you are actually passing in credential, and see also the nevada_scout's answer.
The company domain you have registered in SendGrid should be used to call the MailAddress API. Thus, if your company web site you are registering in SendGrid is www.###.com you should use:
var from = MailAddress("info####.com", "Your Contractor Connection")

send email from MVC 4 ASP.NET app

I am trying to setup simple but complete ASP.NET MVC 4 web app, where I can send email to specific address, I configure the web.config file for SMPT settings and code in controller call, but I am getting error message "The SMTP host was not specified"
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="myEmail#hotmail.co.uk">
<network host="smtp.live.com" port="25" userName="myEmail#hotmail.co.uk" password="myPassword" defaultCredentials="true"/>
</smtp>
</mailSettings>
in controller class
var mailMessage = new MailMessage();
mailMessage.To.Add("yourEmail#hotmail.co.uk");
mailMessage.Subject = "testing 2 ";
mailMessage.Body = "Hello Mr. Aderson";
mailMessage.IsBodyHtml = false;
var smptClient = new SmtpClient { EnableSsl = false };
smptClient.Send(mailMessage);
many thanks
Best Idea to use SMTP mail functionality in .NET + MVC/ASP is this open source codeplex library:
http://higlabo.codeplex.com/
Especially since the default-delivered components in .NET framework does fully support all types of SSL/TSL etc. (implicit/explicit mode as keyword here)
http://higlabo.codeplex.com/
From a quick look you haven't set up the "From" property.
var mailMessage = new MailMessage();
mailMessage.To.Add("yourEmail#hotmail.co.uk");
mailMessage.From = new MailAddress("myEmail#hotmail.co.uk");
mailMessage.Subject = "testing 2 ";
mailMessage.Body = "Hello Mr. Aderson";
mailMessage.IsBodyHtml = false;
Your code and configuration look correct.
Are you sure you have put the system.net/mailSettings element in the web.config in the root directory of your web site?
A common mistake is to put such settings in the web.config in the Views folder.
Incidentally, the MailMessage class implements IDisposable, as does the SmtpClient class from .NET 4. So you should be enclosing both in using blocks.
Not sure if smtp.live.com is still valid http://windows.microsoft.com/en-ca/windows/outlook/send-receive-from-app does not seem to list it
I would check if Port 25 is Blocked if Port 25 is blocked, try Port 587 (Might have to enable SSL for 587)
you missing smptClient.Send(mailMessage); at the end of your code
var mailMessage = new MailMessage();
mailMessage.To.Add("yourEmail#hotmail.co.uk");
mailMessage.From = new MailAddress("myEmail#hotmail.co.uk");
mailMessage.Subject = "testing 2 ";
mailMessage.Body = "Hello Mr. Aderson";
mailMessage.IsBodyHtml = false;
//this what you miss
smptClient.Send(mailMessage);
//
do some thing like this
SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtp], Convert.ToInt32(ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtpport]));
if (ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtpUseCredentials] == "true")
{
smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtpusername], ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtppassword], ConfigurationManager.AppSettings[EFloOnline.Model.Constants.smtp]);
}
else
{
smtp.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
if (SendTo.Count == 0)
{
SendTo.Add(ConfigurationManager.AppSettings[EFloOnline.Model.Constants.ToMail]);
}
foreach (string recipientemail in SendTo)
{
oEmail.To.Add(recipientemail);
try
{
smtp.Send(oEmail);
}
catch (Exception)
{
}
oEmail.To.Clear();
}
}
I wrote a blog post about doing this.
http://www.bgsoftfactory.net/5-steps-to-send-email-with-mvcmailer-from-an-mvc-4-0-application/
I took the easier way, using MVCMailer. Even if sending email from MVC is quite easy, it's a little more complicated to make it nice, while MVCMailer allow to use razor templates to format the body of your email.
You may save yourself some time by using MVCMailer.

Code runs fine on localhost but doesn't execute on gatorhost

I wrote a small website in VWD. I am running it on my home machine using the localhost features of VWD. It runs flawlessly.
Now the backstory. I had a linux server with gatorhost. I had them switch my domain and my server type to windows because i decided to learn asp.net(c#). I had a million problems with them hours on the phone. Issues with unable to connect when you search for my domain and my e-mail features and ftp features where all messed up took them hours to figure it out in multiple calls and tickets.
So now i think i got it all working i load my site through VWD onto my server (www.contentiousweb.com) All of my front end code works fine as far as form validation and links.
When i hit my submit buttons that would execute my c# code nothing happens at all. not a thing. When the forms are filled out wrong the validation works. I got no errors or anything. i like dont know where to start. Is it my code there server how much can i rely on VWD in being right because i cannot rely on my self lol.
Webconfig file. (i swapped out my pw and e-mail)
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="Ralph <********#hotmail.com>">
<network enableSsl="true" host="smtp.live.com" userName="*************#hotmail.com" password="***********" port="587" />
</smtp>
</mailSettings>
</system.net>
Bellow is the button.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string fileName = Server.MapPath("_TextFiles/ContactForm.txt");
string mailBody = File.ReadAllText(fileName);
mailBody = mailBody.Replace("##Name##", nameBox.Text);
mailBody = mailBody.Replace("##Email##", emailBox.Text);
mailBody = mailBody.Replace("##Subject##", subBox.Text);
mailBody = mailBody.Replace("##Message##", MsgField.Text);
MailMessage myMessage = new MailMessage();
myMessage.Subject = "Response from Contact Page";
myMessage.Body = mailBody;
myMessage.From = new MailAddress("******", "Contact");
myMessage.To.Add(new MailAddress("******", " Server"));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMessage);
Message.Visible = true;
ContactTable.Visible = false;
System.Threading.Thread.Sleep(5000);
}
}
}
Any help would be greatly appresciated. i am new and learning but with my experince and problems with hostgator i think that it is something on there end because everything else has been. i am clueless.
Please let me know if there is anymore information i can provide. Thank you for any help
In my own troubleshooting i found this error just now using mozila dev tools.
[18:03:28.399] Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500 # http://contentiousweb.com/ScriptResource.axd?d=EJBSV2JIVC3wCtbtVqDWEZfeOsqUeA-l1kZnjjZKvx15e0cjnzPdj4H78hvszmtfrIhAM96VdUstdDjn1xGAbsydMzIjEQeNWDOz2tihnjEjxDW5esVemHLoHR01oIyUBoZTNPd7atx4-EPBnuVlWYbQIeLdoH_eBXy1j9kav6ac2ptv4Cl8sraaDBGXntVH0&t=ffffffff940d030f:1507
Thanks for any help i am still looking for answers my self.
I got it going. After talking with gatorhost on the phone for four hours we determined that the smtp information they had provided me would not work. They had me change my host to
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="localhost" userName="*************#hotmail.com" password="***********" port="25" />
</smtp>
</mailSettings>
</system.net>
And now it all works no errors. Thank you everyone who helped with ideas.
I don't see in your code assigning the port number or credentials?
This code should work
// SMTP options
string Host = "smtp.mail.emea.microsoftonline.com";
Int16 Port = 587;
bool SSL = true;
string Username = "myname#mydomain.com";
string Password = "mypassword";
// Mail options
string To = "reciever#recieverdomain.com";
string From = "myname#mydomain.com";
string Subject = "This is a test";
string Body = "It works!";
MailMessage mm = new MailMessage(From, To, Subject, Body);
SmtpClient sc = new SmtpClient(Host, Port);
NetworkCredential netCred = new NetworkCredential(Username, Password);
sc.EnableSsl = SSL;
sc.UseDefaultCredentials = false;
sc.Credentials = netCred;
try
{
Console.WriteLine("Sending e-mail message...");
sc.Send(mm);
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}

MVC Form which sends mail

Basically I have an MVC 3 form which sends a mail to my inbox when someone leaves a message on my site.
For some reason it throws an SmtpException with the message: "Failure sending mail."
[HttpPost]
public ActionResult Contact(string name, string email, string message)
{
string From = "contactform#******.com";
string To = "info#******.com";
string Subject = name;
string Body = name + " wrote:<br/><br/>" + message;
System.Net.Mail.MailMessage Email = new System.Net.Mail.MailMessage(From, To, Subject, Body);
System.Net.Mail.SmtpClient SMPTobj = new System.Net.Mail.SmtpClient("smtp.**********.net");
SMPTobj.EnableSsl = false;
SMPTobj.Credentials = new System.Net.NetworkCredential("info#*******.com", "*******");
try
{
SMPTobj.Send(Email);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw new Exception();
}
return View();
}
Could this be something to do with testing it locally rather than testing it on a server?
Do you need to set the SmtpClient.Port to your Host email port?
I would recommend you to try not to rethrow a new exception but just use
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw;
}
rethrowing an exception resets the stack, so you can't reliably trace the source of the error. In this case (without rethrowing) you can probably see the InnerException and Status properties in visual studio usually this will give you more details on the reason of the failure. (Often isp's block port 25 smtp traffic, in case you are testing locally)
Second you can try to configure all the connection details in web.config rather then hard coded in your application that makes it easier to test changes. See below for an example using gmail:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="username#gmail.com">
<network host="smtp.gmail.com" userName="username#gmail.com" password="password" enableSsl="true" port="587" />
</smtp>
</mailSettings>

Categories