Code runs fine on localhost but doesn't execute on gatorhost - c#

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());
}

Related

C# Email with Button_Click Event

I'm trying to create a Button_Click event that sends an email to a gmail account. This is the error I'm getting:
Unable to read data from the transport connection: net_io_connectionclosed.
It's pointing out Line 63 which is:
client.Send(mail);
Here is the code:
protected void Button2_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 465;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.IsBodyHtml = true;
mail.To.Add(new MailAddress("yourclassroomconnection#gmail.com"));
mail.From = new MailAddress("yourclassroomconnection#gmail.com");
mail.Subject = "New Order";
string bodyTemplate = Label2.Text;
mail.Body = bodyTemplate;
client.Send(mail);
}
Any idea where I'm going wrong?
You can use below code as a small test. Try sending email with minimal option. Then add other options like html support. So you can narrow down the problem when you're experimenting a new thing.
try {
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your_email_address#gmail.com");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
} catch (Exception ex)
{
}
You need to generate app specific password and use it here instead of your gmail password.
Please read this tutorial also.
http://csharp.net-informations.com/communications/csharp-smtp-mail.htm
Hard coding the username and password (i.e. the credentials) may be sometimes frustrating.
What you can do is, you can add these credentials in web.config file only once. And you are good to go. Here is the better solution.
web.config file code goes as follows:
<configuration>
<appSettings>
<add key="receiverEmail" value ="ReceiverEmailAddressHere"/>
</appSettings>
</appSettings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="yourclassroomconnection#gmail.com">
<network host="smtp.gmail.com" port="587" enableSsl="true"
userName="YourActualUsername" password="YourActualPassword"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
Please note that you have to change the host according to your gmail account. I am not sure whether the host is correct. I am using outlook to send emails so the host would be smtp-mail.outlook.com
This is how your web.config file would have all the necessary connection credentials that you define at one place at a time. You don't have to use it everytime you use the Email functionality in your application.
protected void btnSendMail_Click(object sender, EventArgs e)
{
MailMessage msg = new MailMessage();
// get the receiver email address from web.config
msg.To.Add(ConfigurationManager.AppSettings["receiverEmail"]);
// get sender email address path from web.config file
var address = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string emailAddress = address.Network.UserName;
string password = address.Network.Password;
NetworkCredential credential = new NetworkCredential(emailAddress, password);
msg.Subject = " Subject text here "
}
SmtpClient client = new SmtpClient();
client.EnableSsl = true;
client.Send(msg); // send the message
The key point here is to access the sender's email address and receiver's email address. Note that I have used (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"); This will navigate your web.config file and search through the hierarchy available in it - Grabs the email address, fails if it doesn't get email address.
Hope this helps. Happy coding!

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.

Sending mail from gmail SMTP C# Connection Timeout

I have been trying to send an email via C# from a gmail account for account registration for my website.
I have tried several ways however the same exception continues to pop up: System.Net.Mail.Smtp Exception - Connection has timed out.
This is what I inluded in my Web.config file:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network"
from="Writely <mrbk.writely#gmail.com>">
<network host="smtp.gmail.com"
port="465"
enableSsl="true"
defaultCredentials="false"
userName="mrbk.writely#gmail.com"
password="******" />
</smtp>
</mailSettings>
</system.net>
where writely is the name of my website, and mrbk.writely#gmail.com is the account I wish to send an email from.
Then in my Account Controller when I connect with my database and save the user in my table, I am creating my MailMessage object and attempting to same the mail by:
using (DBConnection conn = new DBConnection())
{
conn.UserInfoes.Add(userInfo);
conn.SaveChanges();
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mrbk.writely#gmail.com");
mail.To.Add("bernice.zerafa11#gmail.com");
mail.Subject = "Welcome to Writely";
mail.Body = "Test content";
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
Am I missing something or doing something wrong? I read that this is the good way to do this in some other question on stack overflow so I really don't know what's the problem here.
Thanks for your help :)
You need to tell the SmtpClient what settings to use. It does not automatically read this information from the Web.Config file.
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 465);
smtp.Credentials = new NetworkCredential("mrbk.writely#gmail.com", "***");
smtp.EnableSsl = true;
smtp.Send(mail);
gmail requires authentication:
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for TLS/STARTTLS: 587
Port for SSL: 465
so what i did is
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("mrbk.writely#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("bernice.zerafa11#gmail.com", "bernice.zerafa11#gmail.com", "Welcome to Writely", "Test content");
I had the exact same problem and it's resolved after switching the port number from 465 to 587.
I had the problem on "email confirmation", "password recovery", and "sending email" and now all 3 problems are resolved :).
I know it's a pretty old post, but I usually use the existing posts to find answers instead of asking for new questions.
Thank you all for all your helps.
As I have already answered here.
This problem can also be caused by a security configuration in you gmail account.
The correct port is 587, but to authenticate you need to allow access from less secure apps in your gmail account.
Try it here
It worked for me, hope it helps..
Example in asp.net web forms/sharepoint
StringBuilder Body = new StringBuilder();
Body.Append("Your text");
String FromEmail = "you email";
String DisplayNameFromEmailMedico = "display when you receive email";
MailMessage message = new MailMessage();
message.From = new MailAddress(FromEmail, DisplayNameFromEmailMedico);
message.To.Add(new MailAddress("myclient#gmail.com"));
message.Subject = "subject that print in email";
message.IsBodyHtml = true;
message.Body = Body.ToString();
SmtpClient client = new SmtpClient();
NetworkCredential myCreds = new NetworkCredential("yoursmtpemail#gmail.com", "key from email smtp", "");
client.EnableSsl = true;
client.Credentials = myCreds;
client.Send(message);

Operation timed out error

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 .

Email sending error in ASP.NET using C#

This is the code for email sending, but it gives error in try block:
protected void Page_Load(object sender, EventArgs e)
{
EmailUtility email = new EmailUtility();
email.Email = new MailMessage();
string body = email.GetEmailTemplate(Server.MapPath("~/EmailTemplates"), "test.htm");
EmailMessageToken token = new EmailMessageToken();
token.TokenName = "$Name$";
token.TokenValue = "Ricky";
EmailMessageTokens tokens = new EmailMessageTokens();
tokens.Add(token);
//av.LinkedResources.Add(lr);
email.Email.Body = email.ReplaceTokens(body, tokens);
email.Email.To.Add(new MailAddress("sahil4659#gmail.com"));
email.Email.IsBodyHtml = true;
email.Email.From = new MailAddress("sahil4659#gmail.com");
email.Email.Subject = "Hello from bootcamp";
email.SMTP.Host = ConfigurationManager.AppSettings["SMTPServer"];
try
{
email.SMTP.Send(email.Email);
Response.Write("Email sent !");
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}
The error is:
at System.Net.Mail.IisPickupDirectory.GetPickupDirectory()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at _Default.Page_Load(Object sender, EventArgs e) in c:\Users\Sahil\Desktop\Csharp Email Code(2)\Test website\EmailTest.aspx.cs:line 38
I'm going to read your mind and assume that you're seeing System.Net.Mail.SmtpException: Cannot get IIS pickup directory. Googling around, I see references to SMTP configuration you'll need in your web configuration. Your mail server may require credentials, so you might need something like this:
<system.net>
<mailSettings>
<smtp from="fromaddress">
<network defaultCredentials="true"
host="smtpservername" port="smtpserverport"
userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
... in your web.config. Essentially, configure your web app to be able to talk with the SMTP server.
See this thread for more reference, and here's relevant MSDN documentation.

Categories