Contact Form Not Working after hosting Asp.net c# - c#

I know this question that had been asked before but didn't find an appropriate solution to it yet! I hosted my website a few days ago. Everything works normally in my website a part of my contact form that it doesn't work!
The contact form itself doesn't show any errors whatsoever, in fact when I send the details I still get the label message that confirms of sending process, but nothing comes into my email.
The strange thing is when I talked to my host provider, he says to me that there is nothing wrong with my script and they didn't block any port.
I also ran the contact page and done the same process by filling all required fields and it works properly.Any help would much appreciated!
My code :
namespace contact
{
public partial class ContactUs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new
ScriptResourceDefinition
{
Path = "~/scripts/jquery-1.9.1.js"
});
}
protected void btnSub_Click1(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
try
{
if (Page.IsValid)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(txtEmail.Text);
mail.To.Add("myemailaddress");
mail.Subject = txtSubject.Text;
mail.Body = "<b> Sender Name: </b>" + txtName.Text + "
<br/>"
+ "<b> Sender Email: </b>" + txtEmail.Text + "<br/>"
+ "<b> Sender Comment: </b>" + txtMessage.Text;
mail.IsBodyHtml = true;
SmtpClient smtpClient = new
SmtpClient("company's mail", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new
System.Net.NetworkCredential("myemailaddress","password");
smtpClient.Send(mail);
lblmsg.Text = "Thank you for contacting us";
txtName.Enabled = false;
txtEmail.Enabled = false;
txtSubject.Enabled = false;
txtMessage.Enabled = false;
btnSub.Enabled = false;
}
}
catch (Exception ex)
{
lblmsg.Text = "An unexpected error has occured! " + ex.Message;
}
}
}

Related

C# if statement not working

My code works within a local network and I know it will not work outside of the local network as I am using Dns.GetHostEntry to resolve the IP address to hostname and thats fine...
But my if statement is not working, I am getting error "No Host Found" message when trying to resolve hostname from different subnet.
I thought my if statement would stop this error but its not working, can someone help please or tell me how to fix it, code below...
public partial class _Default : System.Web.UI.Page
{
//public string IPaddr1 { get; private set; }
string serviceDesk = "eg#mail.co.uk";
string emailSubject = "MyPc";
string IPaddr = "";
string deviceName = "";
protected void Page_Load(object sender, EventArgs e)
{
getIP();
}
protected void getIP()
{
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDER_FOR"] != null)
{
IPaddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDER_FOR"].ToString();
}
if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
IPaddr = HttpContext.Current.Request.UserHostAddress;
deviceName = Dns.GetHostEntry(IPAddress.Parse(IPaddr)).HostName;
}
if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
deviceName = "Device name could be found";
}
Label1.Text = "IP Address: " + " " + IPaddr;
Label2.Text = "PC Name: " + " " + deviceName;
}
private void EmailVerificationRequest(string recepientEmail, string subject)
{
try
{
using (MailMessage mailMessage = new MailMessage())
{
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("IP address " + IPaddr + "<br/>");
sbEmailBody.Append("Hostname " + " " + deviceName);
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["FromEmail"]);
mailMessage.Subject = subject;
mailMessage.Body = sbEmailBody.ToString();
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
if (string.IsNullOrWhiteSpace(NetworkCred.UserName))
{
smtp.UseDefaultCredentials = true;
}
else
{
smtp.Credentials = NetworkCred;
smtp.UseDefaultCredentials = false;
}
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
try
{
smtp.Send(mailMessage);
}
catch (SmtpException e)
{
}
}
}
catch
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
EmailVerificationRequest(serviceDesk, emailSubject);
Response.Redirect("~/message.aspx");
}
}
From the MSDN Documentation:
If the host name could not be found, the SocketException exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried.
Therefore, I suspect your code isn't getting as far as the third if condition because an exception is being thrown by the call to GetHostEntry(), which you're seeing as the 'error "No Host Found" message'.
The most straightforward way to deal with this is to use a try...catch block to catch the specific exception and handle it, something such as:
try
{
deviceName = Dns.GetHostEntry(IPAddress.Parse(IPaddr)).HostName;
}
catch (SocketException)
{
deviceName = "Device name could be found";
}
This says that if a SocketException occurs during the call to GetHostEntry(), the code is to jump to the catch block, rather than the exception stopping your application.
Note that this assumes that any SocketException means that the IP address wasn't found, but it could mean that the DNS server wasn't contactable, or some other error.
MSDN has quite a lot on exception handling and how try...catch blocks work.
Hope this helps
Before you get a value from a dictionary, you must check if the dictionary contains the key you pass. You achieve this by calling "Contains" method.
if (HttpContext.Current.Request.ServerVariables.Contains("HTTP_X_FORWARDER_FOR"))
{
// Your Code...
}
If you retrieve the content of a dictionary directly and the key you are requesting doesn't exist in the dictionary pairs, the dictionary doesn't return null. Instead, it throws KeyNotFoundException.

C# CodeBehind Error When Using Webforms Front End

I'm attempting to learn about generating an email with attachment(s) using C# CodeBehind. I would like the web page to use the FileUpload control or something similar to select the file on the network.
I get a "Could not find a part of the path 'E:\Web Sites\myNet\Ztest\TrailerPics\'."
I'm wondering if I'm on the right path... or if there is a better approach.
Thx for any help ~j
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
//Get file names from the fileUpload control
var fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
var fileName2 = Path.GetFileName(FileUpload2.PostedFile.FileName);
var fileName3 = Path.GetFileName(FileUpload3.PostedFile.FileName);
//Code block to send email with keyed data
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("DoNotReply#smiley.com");
mail.To.Add("guy.smiley#sesamestreet.com");
mail.Subject = ("IMG");
mail.IsBodyHtml = true;
var client = new SmtpClient("mailout.smiley.com", 25);
string htmlBody;
htmlBody = string.Format("Email Testing for attaching an image");
mail.Body = htmlBody;
//Create the instance of attachments by using the mapped path concatenated with the file name
Attachment addon = new Attachment(Server.MapPath("~/TrailerPics/" + fileName));
Attachment addon2 = new Attachment(Server.MapPath("~/TrailerPics/" + fileName2));
Attachment addon3 = new Attachment(Server.MapPath("~/TrailerPics/" + fileName3));
//Add the attachments as long as the fileUpload control has a file selected
if (FileUpload1.PostedFile.FileName != "")
{
mail.Attachments.Add(addon);
}
if (FileUpload2.PostedFile.FileName != "")
{
mail.Attachments.Add(addon2);
}
if (FileUpload3.PostedFile.FileName != "")
{
mail.Attachments.Add(addon3);
}
//Send mail
client.Send(mail);
//Notify that email was sent
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Email Sent!')", true);
//Close all connections to the files
if (FileUpload1.PostedFile.FileName != "")
{
addon.Dispose();
}
if (FileUpload2.PostedFile.FileName != "")
{
addon2.Dispose();
}
if (FileUpload3.PostedFile.FileName != "")
{
addon3.Dispose();
}
}
catch(Exception ex)
{
//inform user that the email failed
errorLabel.Text = "Something went wrong with the email : " + ex.Message;
}
}

system.io.ioexception the process cannot access the file because it is being used by another process in c# using as an email attachment

I am attaching a pdf file exported from crystal report. When I use this on development PC it works fine. However when I try on clients PC it gives me an exception
system.io.ioexception the process cannot access the file because it is being used by another process
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
try
{
printbanqoute.ExportToDisk(ExportFormatType.PortableDocFormat, "G:\\" + filename);////For Client PC
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
MailMessage mm = new MailMessage();
try
{
string toemail = BLDashboard.email;
string custnm = BLDashboard.custname;
mm.From = new MailAddress("operations#kaem.in", "Kashif Ahhmed");
mm.To.Add(new MailAddress(toemail, custnm));
mm.IsBodyHtml = true;
string name = BLDashboard.custname;
mm.Subject = "Qoutation ";
String Body = "<div>Hello " + name + ",<br> Thank you for considering us for your next Party/Event, here is the qoute for the Party/Event.<br> If any queries you can reach us at 6096464445. <br> Thank You</div>";
mm.Body = Body;
mm.Attachments.Add(new Attachment("G:\\" + filename));///For Cleint PC
SmtpClient sc = new SmtpClient("smtp.kaem.in");
sc.Credentials = new NetworkCredential("operations#kaem.in", "******");
sc.Send(mm);
MessageBox.Show("Email successfully sent to " + toemail);
}
catch (Exception e1)
{
MessageBox.Show("Unable to send email due to following error:\n\n" + e1.Message, "Email send error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
mm.Dispose();//// Later Added this line
}
}
After searching I added
finally
{
mm.Dispose();//// Later Added this line
}
Now it just gave me error no exception.
I tried Disabling and trying, but same issue.
Here's the exception that I am getting:

try-catch block used while smtp exception need to display an error message in the local server

Catch block used whenever there is an exception while using smtp port,but it will throw exception thats fine,it will take a very long time and also the exception message will be directly shown in the code itself,requirement is to display an error message while executing in the localserver and shouldnot come to the code. It should throw exception whenever the server is down or invalid email Id or change in smtp port,Conclusion is the error message should not come directly to the code.It should display an error message and stop the application which should not hang.
protected void Button2_Click(object sender, EventArgs e)
{
//string vv;
//vv = (string)Session["FID"];
DateTime sdt = DateTime.Today;
SqlCommand cmd4 = new SqlCommand();
int flag=0;
String test = DateTime.Now.ToString("dd.MM.yyy");
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
string toemail = GridView1.Rows[i].Cells[2].Text;
string FID1 = GridView1.Rows[i].Cells[0].Text;
GridViewRow row = GridView1.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("CheckBoxMark1");
if (Ckbox.Checked == true)
{
sendMail(toemail);
flag = 1;
//ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email send Succesfully')</script>");
}
if (flag == 1)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email sent on " + test + "')</script>");
cn.Open();
//cmd4.CommandText = "Insert into TrackingFaculty_det (EmailsentDate) values (#EmailsentDate) WHERE FID=#FID";
cmd4.CommandText = "update TrackingFaculty_det SET EmailsentDate=#Email WHERE FID=#FID ";
cmd4.CommandType = CommandType.Text;
cmd4.Connection = cn;
cmd4.Parameters.Clear();
cmd4.Parameters.Add("#Email", SqlDbType.DateTime, 8);
cmd4.Parameters["#Email"].Value = sdt;
cmd4.Parameters.Add("#FID", SqlDbType.VarChar, 10);
cmd4.Parameters["#FID"].Value = FID1;
cmd4.ExecuteNonQuery();
cn.Close();
log.Debug("Info : Insert the Email Sent Date of the faculty");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email cannot be sent')</script>");
}
}
log.Debug("Info : Function used to send mail");
}
public void sendMail(String toemail)
{
try
{
MailMessage mail = new MailMessage();
mail.To.Add(toemail);
mail.From = new MailAddress("manipal.mcis1#gmail.com");
mail.Subject = "Remember Mail";
// string Body = "Please update profile";
//mail.Body = Body;
mail.Body = " Dear Sir/Madam \n\n\n Please update your profile. . \n\n\n Thanks & Regards \n\n\n MCIS,Manipal.";
//mail.Body = "<html><body> <h2" + "align=center>Dear Sir/Madam" + "</h2> Please update ur profile</body></html>";
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 584;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("manipal.mcis1#gmail.com", "manipal15");
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (SmtpException ex)
{
string msg = "Mail cannot be sent:";
msg += ex.Message;
log.Debug("Error: Inside catch block of Mail sending");
log.Error("Error msg:" + ex);
log.Error("Stack trace:" + ex.StackTrace);
throw new Exception(msg);
}
This also arrises with another issue that is whenever it enters for loop its executing the
send(tomail) function even if it is invalid along with this ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email sent on " + test + "')</script>"); line is also executed at every instance.i need to make this work out only when valid EmailID and proper smtp port is available.
Try these lines of code it will work
protected void Button2_Click(object sender, EventArgs e)
{
//string vv;
//vv = (string)Session["FID"];
DateTime sdt = DateTime.Today;
SqlCommand cmd4 = new SqlCommand();
int flag=0;
String test = DateTime.Now.ToString("dd.MM.yyy");
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
string toemail = GridView1.Rows[i].Cells[2].Text;
string FID1 = GridView1.Rows[i].Cells[0].Text;
GridViewRow row = GridView1.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("CheckBoxMark1");
if (Ckbox.Checked == true)
{
sendMail(toemail);
flag = 1;
//ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email send Succesfully')</script>");
}
if (flag == 1)
{
//ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email sent on " + test + "')</script>");
cn.Open();
//cmd4.CommandText = "Insert into TrackingFaculty_det (EmailsentDate) values (#EmailsentDate) WHERE FID=#FID";
cmd4.CommandText = "update TrackingFaculty_det SET EmailsentDate=#Email WHERE FID=#FID ";
cmd4.CommandType = CommandType.Text;
cmd4.Connection = cn;
cmd4.Parameters.Clear();
cmd4.Parameters.Add("#Email", SqlDbType.DateTime, 8);
cmd4.Parameters["#Email"].Value = sdt;
cmd4.Parameters.Add("#FID", SqlDbType.VarChar, 10);
cmd4.Parameters["#FID"].Value = FID1;
cmd4.ExecuteNonQuery();
cn.Close();
log.Debug("Info : Insert the Email Sent Date of the faculty");
}
}
log.Debug("Info : Function used to send mail");
}
public void sendMail(String toemail)
{
try
{
MailMessage mail = new MailMessage();
mail.To.Add(toemail);
mail.From = new MailAddress("manipal.mcis1#gmail.com");
mail.Subject = "Remember Mail";
// string Body = "Please update profile";
//mail.Body = Body;
mail.Body = " Dear Sir/Madam \n\n\n Please update your profile. . \n\n\n Thanks & Regards \n\n\n MCIS,Manipal.";
//mail.Body = "<html><body> <h2" + "align=center>Dear Sir/Madam" + "</h2> Please update ur profile</body></html>";
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("manipal.mcis1#gmail.com", "manipal15");
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (SmtpException ex)
{
string msg = "Mail cannot be sent because of the server problem:";
msg += ex.Message;
log.Debug("Error: Inside catch block of Mail sending");
log.Error("Error msg:" + ex);
log.Error("Stack trace:" + ex.StackTrace);
Response.Write(msg);
//throw new Exception(msg);
}
The time that it needs is the time it needs to "understand" that something is not ok (tehre could different reasons that smtp fails, naturally) .
In you concrete code I see that you re - raise an exception, which is according to the your requirements is not what you want, so probabbly better solution could be:
catch (SmtpException ex)
{
string msg = "Mail cannot be sent:";
msg += ex.Message;
log.Debug("Error: Inside catch block of Mail sending");
log.Error("Error msg:" + ex);
log.Error("Stack trace:" + ex.StackTrace);
SendAsyncMessage(msg);//just an example
}
For client side notification you can use whatever you want. There are different libraries for that:
Toast from John Papa
Bootstrap3 alerts
and so on ...
If this is not what you're asking for, please clarify.

how to implement while loop for processing when clicking

I hope you can help me with this problem. When I click a Email button, it takes few seconds to process before sending successfully. I need to put process image on but how to implement with "while" loop for processing.
Here is code: i think i should implement with client.Send(msg); for processing. How does it work? I will appreciate your example code. Thanks! (I am using C# and WPF)
private void BtnSendEmailClick(object sender, RoutedEventArgs e)
{
SmtpClient client = null;
MailMessage msg = null;
try
{
msg = new MailMessage
{
From = new MailAddress("me#hotmail.com", "Me Hotmail")
};
msg.To.Add(txtEmailAddress.Text);
msg.Priority = MailPriority.High;
msg.Subject = "Blah blah";
msg.Body =
"<!DOCTYPE html><html lang='en' xmlns='http://www.w3.org/1999/xhtml'>" +
"<head> </head>" +
"<body>" +
"<h3>Message</h3>" +
"<p>" + lblEmailMessage.Content + "</p>" +
"</body>" +
"</html>";
msg.IsBodyHtml = true;
client = new SmtpClient
{
Host = "smtp.live.com",
Port = 25,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("me#hotmail.com", "password"),
DeliveryMethod = SmtpDeliveryMethod.Network
};
//how to implement while loop for processing
client.Send(msg);
lblMessage.Content = "Successfully sent to your Mail!";
}
catch (Exception ex)
{
lblMessage.Content = ex.Message;
}
}
You will need to return instantly, and use a BackgroundWorker to send the email. Once it is finished, you can use the Dispatcher to notify the GUI. See http://msdn.microsoft.com/en-us/magazine/cc163328.aspx for more details.
See also How to use WPF Background Worker.
Are you wanting to display an image to indicate that the program is doing something (progress indicator)?
In that case you need to do the work of sending the email on a separate thread. You can do this in several ways. The easiest (if you are using .NET 4) is to use the await and async keywords. Simply display the image before starting your work. You'll need to extract the code that actually sends the email into a new method also. Like this:
private void BtnSendEmailClick(object sender, RoutedEventArgs e)
{
// Display progress image
progressImage.Visibility = System.Windows.Visibility.Visible;
string errorMessage = await SendEmail();
if (errorMessage == null)
{
lblMessage.Content = "Successfully sent to your Mail!";
}
else
{
lblMessage.Content = errorMessage;
}
progressImage.Visibility = System.Windows.Visibility.Hidden;
}
private async Task<string> SendEmail()
{
try
{
var msg = new MailMessage
{
From = new MailAddress("me#hotmail.com", "Me Hotmail")
};
msg.To.Add(txtEmailAddress.Text);
msg.Priority = MailPriority.High;
msg.Subject = "Blah blah";
msg.Body =
"<!DOCTYPE html><html lang='en' xmlns='http://www.w3.org/1999/xhtml'>" +
"<head> </head>" +
"<body>" +
"<h3>Message</h3>" +
"<p>" + lblEmailMessage.Content + "</p>" +
"</body>" +
"</html>";
msg.IsBodyHtml = true;
var client = new SmtpClient
{
Host = "smtp.live.com",
Port = 25,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("me#hotmail.com", "password"),
DeliveryMethod = SmtpDeliveryMethod.Network
};
//how to implement while loop for processing
client.Send(msg);
return "Successfully sent to your Mail!";
}
catch (Exception ex)
{
return ex.Message;
}
}
One final note: Be sure that you don't touch any UI components in your 'async' method as there is no guarantee that the code will be running on the UI thread. If you need more information returned from the async method you'll have to create a custom structure to contain the result and return it from that SendEmail() method.

Categories

Resources