i have problem durin verifying user by email...here is my code for registtration page..
protected void btnsignup_Click(object sender, EventArgs e)
{
MailMessage msg;
//SqlCommand cmd = new SqlCommand();
string ActivationUrl = string.Empty;
string emailId = string.Empty;
try
{
//Sending activation link in the email
msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
emailId = txtemail.Text.Trim();
//sender email address
msg.From = new MailAddress("xyz#gmail.com");
//Receiver email address
msg.To.Add(emailId);
msg.Subject = "Confirmation email for account activation";
//For testing replace the local host path with your lost host path and while making online replace with your website domain name
ActivationUrl = Server.HtmlEncode("http://localhost:51049/ActivateAccount.aspx?CustomerId=" + FetchUserId(emailId) + "&EmailId=" + emailId);
msg.Body = "Hi " + txtName.Text.Trim() + "!\n" +
"Thanks for showing interest and registring in <a href='Home.aspx'> e2e website <a> " +
" Please <a href='" + ActivationUrl + "'>click here to activate</a> your account and enjoy our services. \nThanks!";
msg.IsBodyHtml = true;
smtp.Credentials = new NetworkCredential("xyz#gmail.com", "xxxxxx");
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.Send(msg);
if (result > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Confirmation Link to activate your account has been sent to your email address');window.location='LoginPage.aspx'", true);
ClearControl(this);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Account has not been created.');'", true);
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
return;
}
finally
{
con.Close();
}
}
protected string FetchUserId(string emailId)
{
SqlCommand cmd = new SqlCommand("select CustomerId from tbl_CustomerRegistration WHERE CustomerEmail=#CustomerEmail", con);
cmd.Parameters.AddWithValue("#CustomerEmail", emailId);
string CustomerId = cmd.ExecuteScalar().ToString();
return CustomerId;
}
and code for ActivateMyAccount.aspx...
SqlCommand cmd = new SqlCommand();
try
{
if ((!string.IsNullOrEmpty(Request.QueryString["CustomerId"])) & (!string.IsNullOrEmpty(Request.QueryString["CustomerEmail"])))
{
//approve account by setting Is_Approved to 1 i.e. True in the sql server table
cmd = new SqlCommand("UPDATE tbl_CustomerRegistration SET Is_Approved=1 WHERE CustomerId=#CustomerId AND CustomerEmail=#CustomerEmail", con);
cmd.Parameters.AddWithValue("#CustomerId", Request.QueryString["CustomerId"]);
cmd.Parameters.AddWithValue("#CustomerEmail", Request.QueryString["CustomerEmail"]);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int result= cmd.ExecuteNonQuery();
if(result>0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Your account has been activated. You can login now');window.location='LoginPage.aspx'", true);
}
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
return;
}
finally
{
con.Close();
cmd.Dispose();
}
}
user is getting email after registration but the problem is when user click on verify link then a field in database name as Is_Aprroved is not gettting updated ...thank u ..please help me
Related
How to check failure response in email send method using Asp.Net.
The Problem is i didn't get the failure exception.
Please suggest better way.
Here is my code, i'm trying to access the email failure exception...
public static bool sendMail(string strTo, string strSubject, string strName, string strbody)
{
try
{
strName = strName == "" ? "Sir/Madam" : ("Dear " + strName + ",");
StringBuilder mailbody = new StringBuilder();
SmtpClient mailClient = null;
MailMessage message = null;
mailClient = new SmtpClient();
message = new MailMessage();
mailClient.Host = ConfigurationManager.AppSettings["SMTP_MAIL_SERVER"];
mailClient.Port = int.Parse(ConfigurationManager.AppSettings["PORT"]);
//network credentials
string strMailUserName = ConfigurationManager.AppSettings["FROM_ADDR"];
string strMailPassword = ConfigurationManager.AppSettings["FROM_ADDR_PASS"];
string strWebSiteURL = ConfigurationManager.AppSettings["LinkTosite"];
mailClient.EnableSsl = true;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strMailUserName, strMailPassword);
mailClient.UseDefaultCredentials = true;
mailClient.Credentials = SMTPUserInfo;
string strFromMail = ConfigurationManager.AppSettings["FROM_ADDR"];
MailAddress fromAddress = new MailAddress(strFromMail, "TEST (Administrator)");
message.From = fromAddress;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
//to mail address
message.To.Add(strTo);
message.Subject = "ChatOnGo : " + strSubject;
//mailbody.AppendFormat("<link href='" + strWebSiteURL + "admin/css/bestlogin.css' rel='stylesheet' type='text/css' />");
mailbody.AppendFormat("<div class='dlogin_bg'><div class='dlogin_bg_top'></div><div class='dlogin_bg_bottom'><h2>" + strName + "</h2>");
mailbody.AppendFormat(strbody);
mailbody.AppendFormat("<br/><br/><span>Regards,<br /><a href='" + strWebSiteURL + "'>ChatOnGo Admin</a></span></div></div>");
message.Body = mailbody.ToString();
message.IsBodyHtml = true;
mailClient.SendMailAsync(message);
message = null;
mailClient = null;
return true;
}
catch (SmtpFailedRecipientsException ep)
{
Console.WriteLine(ep.Message);
return false;
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
return false;
}
}
I assume you are using gmail to send email.
You should send the email at least once and if the email is not valid you will receive failure notification.
You can create a nightly/hourly job to check these failure emails and mark them as invalid in your database.
Below is the link to read emails programatically :
http://www.aspsnippets.com/Articles/Fetch-and-read-email-messages-with-attachments-from-GMAIL-POP3-mail-server-in-ASPNet.aspx
I hope this helps!
I am not sure but can you try to send mail without Async (SendMailAsync), just try to call normal send method, probably you will get exception details.
I am a newcomer in .net , my problem is related to email. This code is well performed on my localhost. This is code of my enquiry.aspx.cs:-
protected void Button1_Click(object sender, EventArgs e)
{
Mail mm = new Mail();
if (DropDownList3.SelectedItem.Text == "--Select--")
{
Label5.Text = "Please Select Course";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
}
else if (TextBox1.Text == "")
{
Label5.Text = "Please Enter Name";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
TextBox1.Focus();
}
else if (mm.checkValidemail(TextBox2.Text) == false)
{
Label5.Text = "Please Enter E-Mail ID";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter E-Mail ID');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter E-Mail ID'); </script>");
TextBox2.Focus();
}
else if (mm.checkValidmobile(TextBox3.Text) == false)
{
Label5.Text = "Please Enter Mobile Number";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Mobile Number');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Mobile Number'); </script>");
TextBox3.Focus();
}
else
{
myenquiry ee = new myenquiry();
//myenquiry ee=new myenquiry();
int i = ee.add_enquiry(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, "-", "-", "NORMAL ENQUIRY FROM SITE", TextBox11.Text, DropDownList3.SelectedItem.Text, TextBox12.Text,locationlst.SelectedItem.Text);
if (i == 1)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(" Enquiry " + "<shila#gmail.com> ");
message.To.Add(new MailAddress("shu#gmail.com"));
message.CC.Add(new MailAddress("va_aone#yahoo.com"));
message.Subject = "Enquiry from CMC site";
string p = "<b>Name: </b>" + TextBox1.Text;
p += "<br><b>Mobile:</b> " + TextBox3.Text;
p += "<br><b>Mail ID:</b> " + TextBox2.Text;
p += "<br><b>Address:</b> " + TextBox4.Text;
p += "<br><b>City:</b> " + TextBox5.Text;
p += "<br><b>Location:</b>" + locationlst.SelectedItem.Text;
p += "<br><b>College:</b> " + TextBox11.Text;
p += "<br><b>Course:</b> " + DropDownList3.SelectedItem.Text;
p += "<br><b>Query:</b> " + TextBox12.Text;
message.Body = p;
message.IsBodyHtml = true;
SmtpClient SMTPServer = new SmtpClient("localhost");
try
{
SMTPServer.Send(message);
//result = "Your Enquiry has been Submitted !!";
Label5.Text = "Your Enquiry has been Submitted !!";
//Response.Write("<script language=JavaScript> alert('Your Enquiry has been Submitted !!'); </script>");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox11.Text = "";
TextBox12.Text = "";
DropDownList3.SelectedIndex = 0;
}
catch
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
//Response.Write("<script language=JavaScript> alert('Server Problem !!Your Enquiry Not Submitted'); </script>");
}
}
else
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
}
}
and this is my appcode folder enquiry.cs:-
public class myenquiry
{
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=group;Integrated Security=True");
SqlCommand comm = new SqlCommand();
int result = 0;
public int add_enquiry(string nam,string email,string mob,string adr,string cit,string state,string country,string zip,string college,string tech,string query,string loc)
{
try
{
comm.Connection = conn;
comm.CommandText = "insert into enquiry(name,email,mobile,address,city,state,country,zip,college,technology,query,edate,location) values('" + nam + "','" + email + "','" + mob + "','" + adr + "','" + cit + "','" + state + "','" + country + "','" + zip + "','" + college + "','" + tech + "','" + query + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','"+loc+"')";
conn.Open();
comm.ExecuteNonQuery();
result = 1;
}
catch(Exception ee)
{
result = 0;
}
finally
{
conn.Close();
}
return result;
}
}
this is well perform on local. But at the server the appcode enquiry.cs is not called on enquiry.aspx.cs and the value of int i is becoming 0, so the else part is executing. Why?
You seem to have a hard coded connection string in the myenquiry class. If you are not dynamically setting the connection string from a configuration file or otherwise, the insert method will try to use that string which points to your local. Assuming your server is a different domain/machine with no access to your local DB, the connection will definitely fail, giving you the result 0.
As Shree.pat18 says Don't make hardcodded connection string in class file.instead of this make your connection string in web.config file something like this in your configuration tag
<connectionStrings>
<add name="cn" connectionString="Data Source=USER-PC;Initial Catalog=group;Integrated Security=True"/>
</connectionStrings>
Here I am in a strange situation. When I send the email from localhost it is working fine but when I upload the page to the server and try to send email, I get the following error
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
I'm displaying the error message in a label for testing purpose and the try is also misplaced I know, I will set it later.
the code I am using is
if (Page.IsValid)
{
try
{
StringBuilder message = new StringBuilder();
message.Append("Hello My Name is ");
message.Append(txtName.Text);
message.AppendLine();
message.AppendLine("My Contact Number " + txtContactNumber.Text.ToString());
message.AppendLine();
message.AppendLine();
message.AppendLine("My Email Id Is " + txtFromEmailAddress.Text.ToString());
message.AppendLine();
message.Append(txtEmailBody.Text);
MailMessage mailMessage = new MailMessage("xxx#gmail.com", "yyy#gmail.com");
mailMessage.Subject = "New Client Query";
mailMessage.Body = message.ToString();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 25);
//smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "xxx#gmail.com",
Password = "password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
txtContactNumber.Text = "";
txtFromEmailAddress.Text = "";
txtName.Text = "";
txtEmailBody.Text = "";
lblEmailStatus.Text = "Email Sent Successfully.";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
catch(Exception ex)
{
lblEmailStatus.Text = ex.Message + " <br> " + ex.Source;
}
}
else
{
lblEmailStatus.Text = "Error! Email Not Sent ";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
I have googled for a couple of hours and checked links at this site as well but I still cant figure it out.
Now I request you guys here if any one have any solutions / hint.
Try this
public string SendEmailTest(String EmailMessage, String FromMail, String MailPassword, String MailServer, String To, String CC, String BCC, String DisplayName, String Subject, String Attachment)
{
try
{
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress;
fromAddress = new MailAddress(FromMail);
smtpClient.Host = MailServer;
smtpClient.Port = 25;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(FromMail, MailPassword);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = SMTPUserInfo;
message.From = fromAddress;
message.To.Add(new MailAddress(To, DisplayName));
if (CC != "")
message.CC.Add(new MailAddress(CC, DisplayName));
if (BCC != "")
message.Bcc.Add(new MailAddress(BCC, DisplayName));
message.Subject = Subject;
message.IsBodyHtml = true;
message.Body = EmailMessage;
if (Attachment != "")
message.Attachments.Add(new Attachment(Attachment));
message.Priority = MailPriority.High;
smtpClient.Send(message);
return "SendEmail";
}
catch (Exception ex)
{
return "Email :" + ex;
}
}
i got the reason finally .
the email i was sending emails from was kind of hacked some days before and for the security reasons google team had kind of marked my email as unsecure . i changed the emails address and it is working fine thanks you all.
Based on the Google Gmail Documentation it would appear that the Port should be 587 not 25. I found a few other questions that seem to be related here and here.
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;
i am making a windows phone app in which i want to give the forgot password functionality.
the app will send a email to stored email id of the user when he will press on forget password button.
As there is no smtp class available in windows phone , so i want to make a asp.net web api which will receive email id(and password) from the app and will send an email to that id.
I am new in web services and have 0 knowledge of this
please guide me how to achieve this task and if anyone can provide the code, there must be some web service available like this.
Here is an example of a function that sends an email you can use. Also, there are couple links below that can guide you in creating web service in ASP.NET
In reality, you don’t need to create a web service for this (although it’s recommended). You can create a quick and dirty web form where you pass parameters like this example.com/sendemail.aspx?account=jack.smith&id=223232343
private static void SendEmail(string from, string from_name, string to, string cc, string bcc, string subject, string body, bool isHtml)
{
SmtpClient mailClient = new SmtpClient(Config.SmptSettings.Server);
mailClient.Credentials = new NetworkCredential(Config.SmptSettings.UserName, Config.SmptSettings.Password);
mailClient.Port = Config.SmptSettings.Port;
MailMessage message = new MailMessage();
if (!string.IsNullOrEmpty(from_name))
{
message.From = new MailAddress(from, from_name);
}
else
{
message.From = new MailAddress(Formatter.UnFormatSqlInput(from));
}
message.To.Add(new MailAddress(to));
if (!string.IsNullOrEmpty(bcc, cc))
{
message.CC.Add(cc);
message.Bcc.Add(bcc);
}
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = isHtml;
mailClient.EnableSsl = Config.SmptSettings.SSL;
mailClient.Send(message);
}
## Call this function in your WebApi controller ##
private void sendEmailViaWebApi()
{
string subject = "Email Subject";
string body = "Email body";
string FromMail = "shahid#reckonbits.com.pk";
string emailTo = "reciever#reckonbits.com.pk";
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.reckonbits.com.pk");
mail.From = new MailAddress(FromMail);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("shahid#reckonbits.com.pk", "your password");
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
}
For those using .NET Core, note that there is currently no support for sending emails.
See the following issue for .NET Core via GitHub:
https://github.com/dotnet/corefx/issues/1006
A an alternative solution has been implemented - MailKit:
https://github.com/jstedfast/MailKit
string random;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string s1 = string.Empty;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select EmailId from tblEmail where EmailId='" + txtemail.Text + "'", con);
SqlDataReader dr =cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
s1 = dr.GetString(0);
}
}
dr.Close();
if (s1.Equals(txtemail.Text))
{
Session["Email"] = txtemail.Text;
try
{
Random rndm = new Random();
random = rndm.Next(99999).ToString();
MailMessage message = new MailMessage();
message.From = new MailAddress("yourid#gmail.com");
message.To.Add(new MailAddress(txtemail.Text));
message.Subject = " Hello... This is Your Serial No to change your password:";
message.Body = random.ToString();
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;//Gmail port number
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("yourid#gmail.com", "yourpassword");
client.Send(message);
SqlCommand cmd1 = new SqlCommand("insert into tblRandom values('" + txtemail.Text + "','" + random.ToString() + "')", con);
cmd1.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Security Code Successfully Sent in Your Email Id')</script>");
Response.Redirect("~/anotherpage.aspx");
}
catch (Exception)
{
// Response.Write(ee.Message);
lblmsg.Text = "Please Enter Email-Id..";
lblmsg.Visible = true;
//MessageBox.Show("Please Enter Email-ID");
//Response.Write("<script>alert('Please Enter Email-ID')</script>");
}
}
else
{
lblmsg.Text = "Please Enter Correct Email-Id..";
lblmsg.Visible = true;
}
}
I have some text boxes like name,email address,phone no. and comment on my page.
I have to send the values to my email address..
How should I do this??
I am doing:
protected void btnSubmit_Click(object sender, EventArgs e)
{
SmtpClient client = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
SmtpClient.Host = "localhost";
SmtpClient.Port = 25;
message.From = fromAddress;
message.To.Add("xyz#gmail.com");
message.Subject = "Feedback";
message.IsBodyHtml = false;
message.Body = txtComment.Text;
SmtpClient.Send(message);
Response.Write("Email successfully sent.");
}
catch (Exception ex)
{
Response.Write("Send Email Failed." + ex.Message);
}
}
and I am getting the following error:
An object reference is required for the nonstatic field, method, or property 'System.Net.Mail.SmtpClient.Send(System.Net.Mail.MailMessage)'
SmtpClient.Host = "localhost";
SmtpClient.Port = 25;
~~~~~~~~~~~~~~~~~~~~
SmtpClient.Send(message);
These lines are attempting to use members of the class SmtpClient. However, as these members are not defined as static, you need to refer to your instance of that class, which you have called client.
Try
client.Host = "localhost";
client.Port = 25;
~~~~~~~~~~~~~~~~~~~~
client.Send(message);
Also, have a read of this article on the differences between class and instance members.
Finally, as SmtpClient implements IDisposable, I would change your code to wrap it in a using block, as this will ensure you are correctly cleaning up your SMTP session after you are finished with it.
using (SmtpClient client = new SmtpClient())
{
// YOUR CODE
}
public static string sendMail(string to, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
if (to == "")
to = fromAddress.Address;
MailAddressCollection m = new MailAddressCollection();
m.Add(to);
mail.Subject = subject;
mail.From = fromAddress;
mail.Body = body;
mail.IsBodyHtml = true;
mail.ReplyTo = fromAddress;
mail.To.Add(m[0]);
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(fromAddress.Address, "XXXX");//"XXXX" is the password of the sender.
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mail);
return "done";
}
catch (Exception ex)
{
return ex.Message;
}
}
i had done this:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailMessage mailmsg = new MailMessage();
string name = txtName.Text.ToString();
string contact = txtPhoneNo.Text.ToString();
string comment = txtComment.Text.ToString();
string checkIn = txtCheckIn.Text.ToString();
string from = txtEmail.Text.ToString();
mailmsg.To.Add("recipientemailid#gmail.com");
mailmsg.From = new MailAddress(from.Trim());
mailmsg.Subject = "Test message";
mailmsg.Body = "This Query is submitted by user " + name.Trim() + ", "+ contact.Trim() + ", " + comment.Trim() + ", " + checkIn.Trim();
mailmsg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential("recipientemailid#Gmail.com", "password");
client.Credentials = credentials;
try
{
//try to send the mail message
client.Send(mailmsg);
Response.Write("sent!");
}
catch
{
//some feedback if it does not work
Response.Write("failed!");
}
}
Try
client.Host = "localhost";
client.Port = 465;
~~~~~~~~~~~~~~~~~~~~
client.Send(message);
Do not try to use or manage disposable emails with this because you will be clearly exposed to spam-trappers. Your code is open and very easy to identify who is using the code and from where.