从现有表中发送C#中的电子邮件而不是新创建的表

时间:2015-11-05 13:13:10

标签: c# sql sql-server

这是我的C#代码,它的工作原理是它创建一个名为Users的新表,并使用存储过程从该表中获取值,然后向表中的所有用户发送一封电子邮件。我是c#的新手,需要知道如何更改此代码以从名为Users的“现有”表中获取数据,而不是创建它并从新创建的表中获取信息。

public partial class emailgroup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void SendBulkEmail(object sender, EventArgs e)
    {
        DataTable dtUsers = new DataTable();
        string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("Users_GetEmails", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(dtUsers);
                    string subject= txtSubject.Text; // Text in Subject
                    string body = txtBody.Text; // Text in Message Body

                    //Using Parallel Multi-Threading send multiple bulk email.
                    Parallel.ForEach(dtUsers.AsEnumerable(), row =>
                    {
                        SendEmail(row["Email"].ToString(), subject, string.Format(body, row["UserName"]));
                    });
                    {
                        Response.Redirect("login.aspx");
                    }
                }
            }
        }
    }

    private bool SendEmail(string recipient, string subject, string body)
    {
        MailMessage mm = new MailMessage("gmailusername", recipient); //(put in gmail username between the "")
        mm.Subject = subject;
        mm.Body = body;
        mm.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential();
        NetworkCred.UserName = "gmailusername"; //gmailusername (put in "")
        NetworkCred.Password = "gmailpassword"; //gmailpassword (put in "")
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        return true;
    }

    protected void txtBody_TextChanged(object sender, EventArgs e)
    {

    }
}

这是我的存储过程。

-- Users_GetEmails
CREATE PROCEDURE Users_GetEmails

AS
BEGIN  
    SET NOCOUNT ON;

    SELECT UserName, Email FROM Users
END

1 个答案:

答案 0 :(得分:1)

以下不会创建新用户表。它通过" Users_GetEmails"从数据库创建新的数据表和获取信息。然后它填充该数据表。您正在从该数据表发送包含该信息的电子邮件。