簡體   English   中英

ASP.NET聯系表單-輸出到電子郵件和訪問數據庫

[英]ASP.NET Contact Form - output to email and access database

我是ASP.NET的新手,我正在嘗試創建一個聯系表單,該表單在提交時發送電子郵件,以及將數據存儲在數據庫中。

我已經閱讀了許多教程,並且對使用電子郵件設置基本聯系表感到很滿意-但是我在數據庫部分遇到了麻煩。

如果您曾經做過此事,或者可以提供任何有助於我完成此任務的信息,請告訴我。

我正在運行ASP.NET 2.0

提前致謝。

我對C#和ASP.NET(IT專業一年級學生)都是新手。 直到一個月前,我什至從未看過C#代碼,更不用說用C#編寫任何程序了。 我也一直在梳理互聯網來解決這個問題。 經過一周的修改,我終於弄明白了。 下面的代碼將允許您創建一個ASP.NET“聯系我們”電子郵件表單,並將該表單中的信息發送到SQL Server數據庫。 我希望這可以幫助某人避免我經歷的同樣的煩惱! (如果有人知道更有效地編程的方法,我很想聽聽您的想法。)

這是表單上附加的ASPX.CS文件的代碼:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM