ASP.NET Contact Form - output to email and access database - asp.net

I am new to ASP.NET, and I am trying to create a contact form which sends an email at submission as well storing the data in a database.
I have read numerous tutorials, and I am pretty comfortable with a basic contact form to email setup - but I am having trouble with the database part of it.
Please let me know if you have ever done this, or if you could provide any information that would assist me with this task.
I am running ASP.NET 2.0
Thanks in advance.

I'm very new to both C# and ASP.NET (first year IT student). Up until a month ago, I'd never even viewed C# code, much less programmed anything in C#. I, too, have been combing the internet for a solution to this problem. After a week of tinkering with some code, I finally figured it out. The below code will allow you to create an ASP.NET "Contact Us" email form, and will send the information in the form to a SQL Server database. I hope this helps someone to avoid the same aggravation I went through! (If anyone knows a way to program this more efficiently, I'd love to hear your thoughts.)
HERE IS THE CODE FOR THE ASPX.CS FILE ATTACHED TO THE FORM:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Code for the Reset event (will reset form data):
protected void Reset(object s, EventArgs e)
{
fname.Text = "";
lname.Text = "";
email.Text = "";
phone.Text = "";
comments.Text = "";
}
//Code for the SendMail Event; will send email and write info in email into database:
protected void SendMail(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(email.Text);
mail.To.Add("EMAIL ADDRESS WHERE YOU'D LIKE THE MESSAGE SENT");
mail.Subject = "Contact Us";
mail.IsBodyHtml = true;
mail.Body += "First Name: " + fname.Text + "<br />";
mail.Body += "Last Name: " + lname.Text + "<br />";
mail.Body += "Comments: " + comments.Text + "<br />";
mail.Body += "Phone Number: " + phone.Text + "<br />";
SmtpClient smtp = new SmtpClient();
smtp.Host = "NAME OF SMTP RELAY SERVER";
smtp.Send(mail);
}
protected void insertInfo(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection (ConfigurationManager.ConnectionStrings["WEB.CONFIG CONNECTION STRING NAME"].ToString());
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO TABLE NAME (fname, lname, email, phone, comment)
VALUES (#fname, #lname, #email, #phone, #comments)";
cmd.Connection = myConnection;
cmd.Parameters.Add("#fname", fname.Text);
cmd.Parameters.Add("#lname", lname.Text);
cmd.Parameters.Add("#email", email.Text);
cmd.Parameters.Add("#phone", phone.Text);
cmd.Parameters.Add("#comments", comments.Text);
myConnection.Open();
cmd.ExecuteNonQuery();
myConnection.Close();
}
}

Related

Sending Mail while running the application in IIS

protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(txtEmail.Text.ToString());
mailMessage.Subject = txtSubject.Text.ToString();
mailMessage.To.Add(new MailAddress("my#gmail.com"));
mailMessage.Body = txtSuggestion.Text.ToString();
mailMessage.IsBodyHtml = true;
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new NetworkCredential(txtEmail.Text.ToString(), txtPassword.Text.ToString());
sc.EnableSsl = true;
sc.Send(mailMessage);
lblMessage.Text = "Message Sent Successfully";
txtSubject.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtSuggestion.Text = "";
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
This is the code i am using to send email but whenever i am trying to run the application, i am getting error.
enter image description here
if someone can help why i am getting the error, that would be great.
When using SSL, try using port 465.
https://support.google.com/a/answer/176600
You also have another issue with that code that's un-related to the one you're subscribing. When setting up contact us forms, using the person's email as the FROM field will cause DMARC to fail. You can read up about that here
Also I don't understand why you are using the person's email address and password to connect to gmail with. You should use your own account if you're sending mail.

I need to loop through the email addresses in a table within a SQL Server database and all an Email

I was wondering if someone could help me. I've got a simple Suppliers table that has email addresses for my suppliers.
I need to loop through the email addresses 'SuppEmail' in the Suppliers table in the SQL Server database SpecCars and send them all the email below.
I've been at it for a few days now, looking on-line and trying many different variations, but no matter what I do, it only sends one email
to the first entry frontdesk#jacksauto.com.au in the table and that's it.
If you could help, that would be fantastic. It's an ASP.NET C# solution.
This is the Suppliers table, it just has two records in there:
CREATE table Suppliers
(
SuppId INT IDENTITY(1,1) PRIMARY KEY,
SuppName NVARCHAR(60) NOT NULL,
SuppAddress NVARCHAR(150) NOT NULL,
SuppSuburb NVARCHAR(60) NOT NULL,
SuppState NVARCHAR(30) NOT NULL,
SuppPost NVARCHAR(10) NOT NULL,
SuppPhone NVARCHAR(10) NOT NULL,
SuppEmail NVARCHAR(100) NOT NULL,
SuppCode NVARCHAR(10) NOT NULL
)
Insert into Suppliers (SuppName, SuppAddress, SuppSuburb, SuppState, SuppPost, SuppPhone, SuppEmail, SuppCode)
values ('Jacks Auto', '2 Jill Street', 'Belgrade', 'VIC', '3299', '9555 4457', 'frontdesk#jacksauto.com.au', 'JACBLA')
Insert into Suppliers (SuppName, SuppAddress, SuppSuburb, SuppState, SuppPost, SuppPhone, SuppEmail, SuppCode)
values ('Ultimate Lights', '205 Browns Road', 'Tullamarine', 'VIC', '3011', '9877 2255', 'orders#ultimatlights.com.au', 'ULTTUL')
This is the code snippet :
SqlDataReader sqlData;
SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=SpecCars;Integrated Security=True");
connection.Open();
sqlData = new SqlCommand("Select SuppEmail From Suppliers", connection).ExecuteReader();
int count = sqlData.FieldCount;
while (sqlData.Read())
{
for (int i = 0; i < count; i++)
{
string emailnew = sqlData[i].ToString();
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("myemail.com");
mailMessage.To.Add("myemail.com");
mailMessage.To.Add(emailnew);
//mailMessage.CC.Add(emailnew);
mailMessage.Subject = "Assembly Line Stop";
mailMessage.Priority = MailPriority.High;
mailMessage.Body = "Please be advised that the assembly line at Specialised Cars has STOPPED. You will be notified once the line has started again. Any Services between the LINE STOP and the LINE START will be carried out after 19:00 (7pm).";
mailMessage.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient("smtp-mail.myprovider.com", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential("myemail.com", "password");
smtpClient.Send(mailMessage);
}
}
connection.Close();
Try this:
var mailMessage = CreateMessage();
using(var connection = new SqlConnection("Data Source=.;Initial Catalog=SpecCars;Integrated Security=True"))
{
connection.Open();
using(var sqlData = new SqlCommand("Select SuppEmail From Suppliers", connection).ExecuteReader())
{
while (sqlData.Read())
{
mailMessage.Bcc.Add(emailnew);
}
}
}
SendMessage(mailMessage)
private MailMessage CreateMessage()
{
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress("myemail.com");
mailMessage.To.Add("myemail.com");
mailMessage.Subject = "Assembly Line Stop";
mailMessage.Priority = MailPriority.High;
mailMessage.Body = "Please be advised that the assembly line at Specialised Cars has STOPPED. You will be notified once the line has started again. Any Services between the LINE STOP and the LINE START will be carried out after 19:00 (7pm).";
mailMessage.IsBodyHtml = true;
return mailMessage;
}
private void SendMessage(MailMessage mailMessage)
{
var smtpClient = new SmtpClient("smtp-mail.myprovider.com", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential("myemail.com", "password");
smtpClient.Send(mailMessage);
}
Note: this code can be and should be better. Consider refactoring to get the connectionstring and mail settings from web.config instead of having them hard-coded in your application.
//-----------------
//Hi All, just a quick update:
//Trying8.aspx - Finally Works, it sends LINE STOP Email to every SuppEmail recipient in Suppliers Table
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Trying8.aspx.cs" Inherits="SpecCars.Admin.Trying8" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
//-----------------
//Trying8.aspx.cs - Finally Works, it sends LINE STOP Email to every SuppEmail recipient in Suppliers Table
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Net;
using System.Net.Mail;
using System.Text;
namespace SpecCars.Admin
{
public partial class Trying8 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataReader sqlData;
SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=SpecCars;Integrated Security=True");
connection.Open();
sqlData = new SqlCommand("Select * From Suppliers", connection).ExecuteReader();
using (SmtpClient smtpClient = new SmtpClient("smtp-mail.provider.com", 587))
{
while (sqlData.Read())
{
string emailnew = sqlData["SuppEmail"].ToString();
Label1.Text = emailnew.ToString();
using (MailMessage message = new MailMessage())
{
try
{
message.From = new MailAddress("myemail#outlook.com");
// This doesn't Send (To:) myotheremail#yahoo.com.au
MailAddress AddressTo = new MailAddress("myotheremail#yahoo.com.au");
// This does Send (To:) to SuppEmail recipient in Suppliers Table
message.To.Add(emailnew);
//This does Send a (CC:) myotheremail#yahoo.com.au
message.CC.Add("myotheremail#yahoo.com.au");
message.Subject = "Assembly Line Stop";
message.Priority = MailPriority.High;
message.Body = "Please be advised that the assembly line at Specialised Cars has STOPPED. You will be notified once the line has started again. Any Services between the LINE STOP and the LINE START will be carried out after 19:00 (7pm).";
message.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential("myemail#outlook.com", "password");
smtpClient.Send(message);
// smtpClient.Dispose();
// message.Dispose();
}
catch (Exception ex)
{
//log exceptions here, you can write it to a txt file, or to a label in your form for testing purpose
//we are trying to see if you get an exception..
Label1.Text = ex.Message;
}
}
}
}
}
}
}
//-----------------

An exception of type 'System.Data.SqlClient.SqlException' in login page

I m new into ASP.net, creating a basic login page. I m getting following error when I m trying to compile:
"An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'Table'."
Following is my code, Can anybody explain me what I m doing wrong here?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from Table where username = '" + username.Text + "' ";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("Username Already Exist");
}
conn.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table (username, email, password) values (#username, #email, #password)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#username", username.Text);
com.Parameters.AddWithValue("#email", emailID.Text);
com.Parameters.AddWithValue("#password", passwrd.Text);
com.ExecuteNonQuery();
Response.Redirect("default3.aspx");
Response.Write("Your registration is successful");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
Response.Write("Your form has been submitted");
}
}
Table is a reserved word in T-SQL (for fairly obvious reasons). The quick fix is to explicitly enclose the identifier:
select count(*) from [Table] where ...
A more apt fix would be to give your tables more meaningful names. There's a reason car companies don't name their vehicles Car. It has a high potential for confusion.

how to send email through asp.net web api

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

Error in sending email through asp.net

I'm currently working on a asp.net website using Visual Studio 2010... I'm trying to send email from my contact us page... I'm getting this error:
Warning 9 CA2000 : Microsoft.Reliability :
In method 'Default2.Button1_Click(object, EventArgs)',
call System.IDisposable.Dispose on object 'msg'
before all references to it are out of scope.
c:\Users\toshiba\Documents\Visual Studio 2010\WebSites\Carp-MacDental\ContactUs.aspx.cs 29
C:\...\Carp-MacDental\
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
public partial class Default2 : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string url = Request.Url.AbsoluteUri;
string hyperlink = "<a href='" + url + "'>" + url + "</a>";
NetworkCredential loginInfo = new NetworkCredential("Site#gmail.com", "password");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("Site#gmail.com");
msg.To.Add(new MailAddress(txtEmail.Text));
msg.Bcc.Add(new MailAddress("Site#gmail.com"));
msg.Subject = "Notification from:" + url;
msg.Body = "A message form," + txtName.Text + ", <br/>" + txtMessage.Text;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
lblMessage.Text = "Thank you for contacting us.. we will get back to you as soon as we read your message";
}
}
Its my first time working with this so I'm pretty confused.. Also my mail message that was supposed to be sent through the website wasn't sent...
As Aristos indicated with his link to Msdn, the warning you see is a code analysis warning. Visual Studio has identified that there is a small problem with your code and shows the warning to alert you about the problem.
The problem is that you are creating a couple of instances of classes that implement the IDisposable interface. Classes that implement this interface have a Dispose method that should be called when you are finished with the instance. The Dispose method is used to clean up unmanaged resources that the instance is using behind the scene, thus making sure that memory and other unmanaged resources are freed up for use by other processes.
Both MailMessage and SmtpClient implement this interface. So intances of these classes should have their respective Dispose method called before they go out of scope. The first thought might be to simply add a couple of lines to you existing code:
...
client.Send(msg);
msg.Dispose();
client.Dispose();
...
But a better soultion would probably be to wrap these in using() { } blocks. Doing this will make the compiler insert code that automatically calls the Dispose method, and it will even be called even if there is an exception thrown from inside the using() { } block. Try this:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string url = Request.Url.AbsoluteUri;
string hyperlink = "<a href='" + url + "'>" + url + "</a>";
NetworkCredential loginInfo = new NetworkCredential("Site#gmail.com", "password");
using(MailMessage msg = new MailMessage())
using(SmtpClient client = new SmtpClient("smtp.gmail.com"))
{
msg.From = new MailAddress("Site#gmail.com");
msg.To.Add(new MailAddress(txtEmail.Text));
msg.Bcc.Add(new MailAddress("Site#gmail.com"));
msg.Subject = "Notification from:" + url;
msg.Body = "A message form," + txtName.Text + ", <br/>" + txtMessage.Text;
msg.IsBodyHtml = true;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
lblMessage.Text = "Thank you for contacting us.. we will get back to you as soon as we read your message";
}
That should hopefully get rid of the compiler warning for you. The fact that the email is not really sent is another matter. I cannot help with that without a lot more details. If you need help with that, I suggest you post a new question and add as much info about the problem as possible in that question.

Resources