error when sending email from asp.net contact page - asp.net

Iam trying to send an email from my contact page but I keep getting an error
I have pasted my code below as well as the error message that is appearing.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'
Dim SendPw As New System.Net.Mail.MailMessage
Dim Smtp As New System.Net.Mail.SmtpClient()
SendPw.To.Add(email.Text)
SendPw.From = New System.Net.Mail.MailAddress("shumbasoft#gmail.com")
SendPw.Subject = "Password for you"
SendPw.Priority = Net.Mail.MailPriority.High
SendPw.Body = "This your new password: "
SendPw.IsBodyHtml = False
Smtp.Host = "smtp.gmail.com"
Smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis
Smtp.Send(SendPw)
End Sub

Have you configure IIS ? or make a try with this code, it give good result for me:
Dim msgMail As New MailMessage()
Dim myMessage As New MailMessage()
myMessage.From = New MailAddress("sender's email", "sender`s name and surname")
myMessage.[To].Add("recipient's email")
myMessage.Subject = "Subject"
myMessage.IsBodyHtml = True
myMessage.Body = "Message Body"
Dim mySmtpClient As New SmtpClient()
Dim myCredential As New System.Net.NetworkCredential("email", "password")
mySmtpClient.Host = "your smtp host address"
mySmtpClient.UseDefaultCredentials = False
mySmtpClient.Credentials = myCredential
mySmtpClient.ServicePoint.MaxIdleTime = 1
mySmtpClient.Send(myMessage)
myMessage.Dispose()
you need to import Imports system.net.mail

this did the trick for me!! from the localhost to gmail
Dim Body As String = "From: " + fname.Text + " " + lname.Text + Environment.NewLine + "Email: " + email.Text + Environment.NewLine + Environment.NewLine + "Message" + Environment.NewLine + txtComment.Text
Dim xx As New System.Net.Mail.SmtpClient
xx.EnableSsl = True
xx.Host = "smtp.gmail.com"
Dim cred As New System.Net.NetworkCredential("example#gmail.com", "examplepassword")
xx.Credentials = cred
xx.Send(email.Text, "sendexample#gmail.com ", subject.Text, Body)
ClearFields()
lblEmail.ForeColor = Drawing.Color.Green
lblEmail.Text = "message sent"
lblEmail.Visible = True

Related

try to send email message in C#

I am New in asp.net .plz help
I am trying to send email message in C# with this code
can any body tell me what is wrong with my code ??..it is building with out error but message didn't sent.
if ((!string.IsNullOrEmpty(base.Request["SECURETOKENID"]) && !string.IsNullOrEmpty(base.Request["EMAIL"])) && (base.Request["RESPMSG"] == "Approved"))
{
SqlConnection connection = new SqlConnection(Common.GetConnectionString("DBConnect"));
connection.Open();
SqlCommand command = new SqlCommand(string.Concat(new object[] { "UPDATE VIPPurchases SET PurchaseDate='", DateTime.Now, "', Status=1 WHERE PurchaseCode='", base.Request["SECURETOKENID"], "' AND Status=0" }), connection);
if (command.ExecuteNonQuery() == 1)
{
command = new SqlCommand("SELECT Ct.title, VI.VideoTitle FROM VIPView as VI INNER JOIN VIPPurchases as VP ON VI.catid = VP.VideoCode INNER JOIN categoryppv as Ct ON VP.VideoCode = Ct.catid WHERE VP.PurchaseCode='" + base.Request["SECURETOKENID"] + "' and VI.viewtype='3' AND VI.IsPublished='1'", connection);
string str = (string)command.ExecuteScalar();
command = new SqlCommand("SELECT Value FROM Settings WHERE Name='Email'", connection);
string addresses = (string)command.ExecuteScalar();
command = new SqlCommand("SELECT Fm.FilmmakerEmail, VI.VideoCode, VP.PurchaseCode FROM VIPPurchases as VP INNER JOIN VIPView as VI ON VP.VideoCode = VI.catid INNER JOIN Filmmakers as Fm ON VI.FilmmakerCode = Fm.FilmmakerCode where VP.PurchaseCode='" + base.Request["SECURETOKENID"] + "' and VI.viewtype='3' AND VI.IsPublished='1'", connection);
addresses = addresses + ", " + ((string)command.ExecuteScalar());
command = new SqlCommand("Select Value from Settings WHERE Name='SenderAddress'", connection);
string userName = (string)command.ExecuteScalar();
command = new SqlCommand("Select Value from Settings WHERE Name='SenderPassword'", connection);
string password = (string)command.ExecuteScalar();
command = new SqlCommand("Select Value from Settings WHERE Name='SMTP'", connection);
string str5 = (string)command.ExecuteScalar();
command = new SqlCommand("Select Value from Settings WHERE Name='Port'", connection);
int num = Convert.ToInt32((string)command.ExecuteScalar());
command = new SqlCommand("Select Value from Settings WHERE Name='SSL'", connection);
bool flag = command.ExecuteScalar() == "True";
SmtpClient client = new SmtpClient
{
UseDefaultCredentials = false,
Host = str5,
Port = Convert.ToInt32(num),
Credentials = new NetworkCredential(userName, password),
EnableSsl = flag
};
MailMessage message = new MailMessage
{
Subject = "platformathletics World - Inndividual Registration",
From = new MailAddress(userName)
};
message.To.Add(base.Request["EMAIL"]);
message.IsBodyHtml = true;
message.Body = "<h3>platformathletics World - (" + str + ") Purchase</h3><p>You are allowed to watch training video <b>" + str + "</b> for next 30 days (till " + DateTime.Now.AddDays(30.0).ToString("MMM dd, yyyy hh:mm tt") + "<sup style='color:red'>*</sup>) from now.</p><p>Your ticket number is <b>" + base.Request["SECURETOKENID"] + "</b>.</p><p>Put your ticket number <a href='http://" + HttpContext.Current.Request.Url.Host + "/VIPMovieList.aspx'>here</a> in return box to watch the video.</p><p><a href='http://" + HttpContext.Current.Request.Url.Host + "/login.aspx'>Login</a> or <a href='http:" + HttpContext.Current.Request.Url.Host + "/register.aspx'>register</a> to platformathletics Network to manage your My Pay Per View Purchases section.</p><br /><hr><br /><small>You could be in different time zone other than United States but your ticket will expire in exact 30 days from the time you receive this email.</small>";
client.Send(message);
message = new MailMessage
{
Subject = "platformathletics World - Inndividual Registration",
From = new MailAddress(userName)
};
message.To.Add(addresses);
message.IsBodyHtml = true;
message.Body = "<h3>platformathletics World - (" + str + ") Purchase</h3><p>Your video has been purchased. <i>" + base.Request["EMAIL"] + "</i> is allowed to watch <b>" + str + "</b> for 30 days.</p><p>Confirmation emails are also sent to " + base.Request["EMAIL"] + " and platformathletics Admin.";
client.Send(message);
this.ErrorPanel.Visible = false;
this.SuccessPanel.Visible = true;
}
Am I going on the right path??
Please help me..thanks
You should use try/catch when you actually send the message, you'll get a more descriptiive message of what's going wrong:
try
{
client.Send(message);
}
catch (Exception e)
{
//Handle exception
Console.Write(e.ToString()); //Or use another way to display the message.
}
Try this,
string mailServer;
int port;
string mailId, mailPass;
string subject;
string mailTo;
subject="something";
StringBuilder mailBody = new StringBuilder();
mailTo = "someone#gmail.com";
mailServer = "smtp.gmail.com";
mailId = "something#gmail.com";
myString.Length = 0;
myString.Append("<html><body><div>BODY CONTENT</div></body></html>");
mailPass = "xxxxxx";
port = 587;
MailMessage mail = new MailMessage(mailId, mailTo, subject, myString.ToString());
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(mailServer, port);
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(mailId, mailPass);
smtp.UseDefaultCredentials = false;
smtp.Credentials = nc;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
Change mailTo, mailId, mailPass according to yours.
I'd change :
this.ErrorPanel.Visible = false;
to
this.ErrorPanel.Visible = true;
See if that gives you an error.

TreeView expanding wrong node

I have a TreeView in a VB.NET/ASP.NET Application.
The TreeView is being Populated programmatically as the page loads. However, when i try and expand a node it is expanding the wrong node.
Example:I have a node with 5 children. Nodes one and two have children and when i try and expand node two it expands node one and when i try and expand node one it also expands node one.
I have tried re-organizing the structure of the TreeView and Also tried adding the nodes in one by one and still no luck.
Edit:
Below is the Relevant code from my TreeView :
For Each V2MaterialRow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Material Details'", connection)
Dim FormName As String = command.ExecuteScalar()
connection.Close()
V2MaterialNode = New TreeNode
V2MaterialNode.ToolTip = "V2 Material Details"
V2MaterialNode.Text = FormName & " " & V2MaterialRow("Version")
V2MaterialNode.Value = V2MaterialRow("Qno")
V2MaterialNode.ShowCheckBox = True
V2MaterialNode.NavigateUrl = "V2MaterialDetails.aspx?text=" + V2MaterialRow("Qno")
V2MaterialNode.Target = "_blank"
node.ChildNodes.Add(V2MaterialNode)
connection.Open()
command = New SqlCommand("Select * from Specallinone where qno='" + V2MaterialRow("Qno") + "'", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
For Each PurchaseOrderRow In DS.Tables("PurchaseOrder").Rows
PurchaseOrderNode = New TreeNode
PurchaseOrderNode.ToolTip = "Purchase Order"
PurchaseOrderNode.Text = "Purchase Order - " + PurchaseOrderRow("supplier") + " " + PurchaseOrderRow("Ordernumber")
PurchaseOrderNode.Value = PurchaseOrderRow("Qno")
PurchaseOrderNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + PurchaseOrderRow("Qno") + "&Jobno=" + PurchaseOrderRow("JobNumber") + "&Orderno=" + PurchaseOrderRow("Ordernumber") + "&text=" + Replace(PurchaseOrderRow("supplier"), "&", "$") + ""
PurchaseOrderNode.Target = "_blank"
V2MaterialNode.ChildNodes.Add(PurchaseOrderNode)
Next
Else
datareader.Close()
End If
connection.Close()
For Each LabelRow As DataRow In DS.Tables("AllinOne").Rows
Dim Labelnode = New TreeNode
Labelnode.ToolTip = "PO Labels"
Labelnode.Text = "PO Labels"
Labelnode.Value = LabelRow("Qno")
'Labelnode.ShowCheckBox = True
Labelnode.NavigateUrl = "GeneratePOLabels.aspx?text=" + LabelRow("Qno")
Labelnode.Target = "_blank"
Try
connection.Open()
command = New SqlCommand("Select * from purchaseorder where qno='" + LabelRow("Qno") + "' and Jobnumber<>''", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
Exit For
Else
datareader.Close()
V2MaterialNode.ChildNodes.Add(Labelnode)
End If
Catch ex As Exception
Messagebox.Show("Error in Dispalying the Labels...")
Finally
connection.Close()
End Try
Next
Next
For Each MPORow In DS.Tables("ManualPO").Rows
Dim Supplier As String
connection.Open()
command = New SqlCommand("Select Distinct Supplier from ManualPurchaseOrder where ManualDetailsId='" + MPORow("ManualDetailsId").ToString + "' ", connection)
datareader = command.ExecuteReader()
While datareader.Read()
Supplier = Supplier + datareader.Item("Supplier") + ","
End While
datareader.Close()
connection.Close()
MPONode = New TreeNode
MPONode.Value = MPORow("ManualDetailsId")
MPONode.Text = "Manual PO " & MPORow("ManualDetailsId") & " Supplier:" & Supplier.ToString
Supplier = ""
node.ChildNodes.Add(MPONode)
Dim ManualPODetailsDa As New SqlDataAdapter("Select distinct supplier,Jobnumber,ordernumber,Qno from PurchaseOrder where Ordernumber in (Select Distinct OrderNumber From ManualPurchaseOrder where ManualDetailsId = '" + MPORow("ManualDetailsId") + "') ", connection)
Dim ManualPODetailsDs As New DataSet
ManualPODetailsDa.Fill(ManualPODetailsDs)
For Each ManualPODetailsDR As DataRow In ManualPODetailsDs.Tables(0).Rows
MPODNode = New TreeNode
MPODNode.Value = ManualPODetailsDR("OrderNumber")
MPODNode.Text = "Purchase Order - " + ManualPODetailsDR("supplier") + " " + ManualPODetailsDR("Ordernumber")
MPODNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + ManualPODetailsDR("Qno") + "&Jobno=" + ManualPODetailsDR("JobNumber") + "&Orderno=" + ManualPODetailsDR("Ordernumber") + "&text=" + Replace(ManualPODetailsDR("supplier"), "&", "$") + ""
MPODNode.Target = "_blank"
MPONode.ChildNodes.Add(MPODNode)
Next
Next
For Each Takeoffrow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Take-Off-Sheets'", connection)
Dim FormName As String = command.ExecuteScalar()
TakeOffNode = New TreeNode
TakeOffNode.ToolTip = "Take Off Sheets"
TakeOffNode.Text = FormName & " " & Takeoffrow("Version")
TakeOffNode.Value = Takeoffrow("Qno")
TakeOffNode.ShowCheckBox = True
TakeOffNode.NavigateUrl = "TakeOffSheet.aspx?text=" + Takeoffrow("Qno")
TakeOffNode.Target = "_blank"
node.ChildNodes.Add(TakeOffNode)
command = New SqlCommand("Select count(*) from ManualTakeOffSheet where srecid in (Select Distinct Srecid from Specdetails where Quoteno='" + Takeoffrow("Qno") + "')", connection)
Dim MTS As Integer = 0
MTS = command.ExecuteScalar()
connection.Close()
If MTS > 0 Then
Dim ManualTakeoffnode As New TreeNode
ManualTakeoffnode.ToolTip = "Manual Take Off Sheets"
ManualTakeoffnode.Text = "Manual Take Off Sheets" & " " & Takeoffrow("Version")
ManualTakeoffnode.Value = Takeoffrow("Qno")
ManualTakeoffnode.NavigateUrl = "ManualTakeOffSheet.aspx?text=" + Takeoffrow("Qno")
ManualTakeoffnode.Target = "_blank"
TakeOffNode.ChildNodes.Add(ManualTakeoffnode)
End If
Next
Sometimes if you have a node which shares the same value as another node - unexpected behavior can occur (one node opening when the other is clicked)
Node values must be unique
Debug your code and ensure that all your nodes have a unique value.
The value will be stored in node.Value
In your case, the node.Value is populated from a table.
Ensure that TakeOffNode.Value = Takeoffrow("Qno") does not equal MPODNode.Value = ManualPODetailsDR("OrderNumber")

My textbox is not filled with data

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
TextBox3.Text = Now()
Dim com As New SqlCommand
com.CommandType = CommandType.Text
com.CommandText = "select productname ,productid,productdescreption,price from products order by productname "
com.Connection = con
Dim ad As New SqlDataAdapter
Dim ds As New DataSet
ad.SelectCommand = com
ad.Fill(ds)
DropDownList1.DataSource = ds
DropDownList1.DataTextField = "productname"
DropDownList1.DataValueField = "productid"
'Dim ss As Integer
'ss = Convert.ToInt32(DropDownList1.DataValueField)
'DropDownList1.DataValueField = ss
DropDownList1.DataBind()
Dim com2 As New SqlCommand
com2.CommandType = CommandType.Text
com2.CommandText = "select dealername ,dealerid from dealerin order by dealername "
com2.Connection = con
Dim ad2 As New SqlDataAdapter
Dim ds2 As New DataSet
ad2.SelectCommand = com2
ad2.Fill(ds2)
DropDownList2.DataSource = ds2
DropDownList2.DataTextField = "dealername"
DropDownList2.DataValueField = "dealerid"
DropDownList2.DataBind()
'Dim com3 As New SqlCommand
'com3.CommandType = CommandType.Text
'com3.CommandText = "select distinct productname ,productid,productdescreption from products "
'com3.Connection = con
'Dim ad3 As New SqlDataAdapter
'Dim ds3 As New DataSet
'ad2.SelectCommand = com3
'ad2.Fill(ds3)
'DropDownList3.DataSource = ds3
'DropDownList3.DataTextField = "productdescreption"
'DropDownList3.DataValueField = "productid"
'DropDownList3.DataBind()
End If
End Sub
Dim dss As New DataSet
Public Function getproduct_byid(ByVal productid As Integer) As DataSet
Try
Dim com3 As New SqlCommand
com3.CommandType = CommandType.StoredProcedure
com3.CommandText = "getproduct_byid"
com3.Connection = con
'com.Parameters.AddWithValue("#productid", productid)
Dim adapter3 As New SqlDataAdapter(com3)
adapter3.Fill(dss, "product")
Return dss
Catch ex As Exception
Response.Write("error due to " & ex.Message)
End Try
End Function
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
Try
getproduct_byid(DropDownList1.SelectedValue)
If dss.Tables("product").Rows.Count = 1 Then
TextBox5.Text = dss.Tables("product").Rows(0).Item("price")
End If
Catch ex As Exception
Response.Write("error due to " & ex.Message)
End Try
End Sub
Protected Sub TextBox5_TextChanged(sender As Object, e As EventArgs) Handles TextBox5.TextChanged
Try
Dim a As Double
Dim b As Double
a = TextBox4.Text
b = TextBox5.Text
TextBox6.Text = A * b
Catch ex As Exception
Response.Write("error due to " & ex.Message)
End Try
End Sub
It might be your datatable contain more than 1 row ..
Change this
If dss.Tables("product").Rows.Count = 1 Then
To
If dss.Tables("product").Rows.Count > 0 Then

The thread was interrupted

I am using this code to update database with new values. But it return message The thread was interrupted. What does it mean? What is wrong with my code?
Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("DeskriptivaConnectionString").ConnectionString.ToString()
Dim txtName As Object = DirectCast(FormView1.FindControl("txtName"), TextBox)
Dim txtLastName As Object = DirectCast(FormView1.FindControl("txtLastName"), TextBox)
Dim txtInfo As Object = DirectCast(FormView1.FindControl("txtInfo"), TextBox)
Dim txtCity As Object = DirectCast(FormView1.FindControl("txtCity"), TextBox)
Dim txtPrize As TextBox = DirectCast(FormView1.FindControl("txtPrize"), TextBox)
Dim txtPhone As TextBox = DirectCast(FormView1.FindControl("txtPhone"), TextBox)
Dim txtMail As TextBox = DirectCast(FormView1.FindControl("txtMail"), TextBox)
Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "UPDATE Profiles SET #Name = Name, #LastName = LastName, #Info = Info, #City = City, #Prize = Prize, #Phone = Phone, #Mail = Mail WHERE (UserName = #UserName)"
cmd.Parameters.Add("#Name", System.Data.SqlDbType.NVarChar).Value = txtName.Text
cmd.Parameters.Add("#LastName", System.Data.SqlDbType.NVarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Info", System.Data.SqlDbType.NText).Value = MakeLink(HtmlRemoval.StripTagsCharArray(txtInfo.Text))
cmd.Parameters.Add("#City", System.Data.SqlDbType.NVarChar).Value = txtCity.Text
cmd.Parameters.Add("#Prize", System.Data.SqlDbType.NVarChar).Value = txtPrize.Text
cmd.Parameters.Add("#Phone", System.Data.SqlDbType.NVarChar).Value = txtPhone.Text
cmd.Parameters.Add("#Mail", System.Data.SqlDbType.NVarChar).Value = txtMail.Text
cmd.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Response.Redirect(ResolveClientUrl("~/Profil/"))
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Use Response.Redirect(ResolveClientUrl("~/Profil/"), false) with Context.ApplicationInstance.CompleteRequest(); instead of Response.Redirect(ResolveClientUrl("~/Profil/"))
check Correct use of System.Web.HttpResponse.Redirect blog post for more information
and also your sql parameters # symbol is in wrong place. change as below
UPDATE Profiles SET
Name = #Name, LastName
= #LastName, Info =
#Info, City = #City,
Prize = #Prize, Phone
= #Phone, Mail = #Mail
WHERE (UserName =
#UserName)

advanced search page for web application using vb.net

i created a simple advanced search page for web application, i thought sharing it with you might help beginners
the following is an example of an advanced search page for an employee database using VB.Net
the following is the code behind page
Imports System.Data.OleDb
Partial Class searchme
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mydb As New OleDbConnection
mydb = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |datadirectory|employee.mdb;Persist Security Info=True")
mydb.Open()
Dim sqlstring = "select * from [dataview] where "
If MRNTextBox1.Text <> "" Then sqlstring = sqlstring + "[code] like '%" + CodeNameTextBox1.Text + "%' OR [EmployeeName] like '%" + CodeNameTextBox1.Text + "%' AND "
If GOVDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Governorate] ='" + GOVDDL.SelectedItem.Text + "' AND "
If genderddl.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Gender] ='" + genderddl.SelectedItem.Text + "' AND "
If DateEmploymentFrom.Text <> "" And DateEmploymentTo.Text <> "" Then sqlstring = sqlstring + "[DateEmployment] >= #" + DatumKonvert1.DK1(DateEmploymentFrom.Text) + "# AND [Datepresentation] <= #" + DatumKonvert1.DK1(DateEmploymentTo.Text) + "# AND "
If DepartmentDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Department] ='" + DepartmentDDL.SelectedItem.Text + "' AND "
sqlstring = Left(sqlstring, Len(sqlstring) - 5) + " order by " + OrderByDDL.SelectedItem.Text
Dim myds As New AccessDataSource
myds.DataFile = "~\App_Data\employee.mdb"
myds.SelectCommand = sqlstring
' Dim Mygrid As New GridView
Mygrid.DataSource = myds
Mygrid.DataBind()
' Me.form1.Controls.Add(Mygrid)
mydb.Close()
RecCount.Text = "Filtered Record Count = " + mygrid.Rows.Count.ToString
Session("dsource") = myds
Response.Redirect("sresults.aspx")
End Sub
End Class
you did a good job, also try the following
link text
link text

Resources