2011-12-31 69 views
1

我正在開發一個Web應用程序,爲用戶提供簡短的測驗。系統將檢查由QuizID和IsSent列組成的數據庫中的Quiz表。如何在發送電子郵件後更新'IsSent'列的值?

如果IsSent列(位數據類型)的值爲0(false),系統會將測驗發送給所有用戶。如果它有1,則表示測驗已經發送。

我可以讓應用程序發送電子郵件,但現在我希望系統在發送電子郵件後將IsSent的值更新爲1或true,但我不知道該怎麼做。

誰能告訴我該怎麼做?

我的代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    SendEmailTOAllUser(); 
} 


protected void SendEmail(string toAddress, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml) 
{ 
    SmtpClient sc = new SmtpClient("SMTP (MAIL) ADDRESS"); 
    try 
    { 
     MailMessage msg = new MailMessage(); 
     msg.From = new MailAddress("[email protected]", "OUR SYSTEM"); 
     msg.To.Add(toAddress); 
     msg.Subject = MailSubject; 
     msg.Body = MessageBody; 
     msg.IsBodyHtml = isBodyHtml; 
     //Response.Write(msg); 
     sc.Send(msg); 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 

} 

protected void SendEmailTOAllUser() 
{ 
    string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspTest;Integrated Security=True"; 
    string cmdText = "SELECT QuizID, IsSent FROM dbo.QUIZ"; 
    string cmdText2 = "SELECT Username FROM dbo.employee"; 

    Collection<string> emailAddresses = new Collection<string>(); 
    string link = ""; 
    string body = ""; 

    using (SqlConnection conn = new SqlConnection(connString)) 
    { 
     conn.Open(); 
     // Open DB connection. 
     using (SqlCommand cmd = new SqlCommand(cmdText, conn)) 
     { 
      SqlDataReader reader = cmd.ExecuteReader(); 
      if (reader != null) 
      { 
       while (reader.Read()) 
       { 
        if (!(bool)reader["IsSent"]) 
        { 
         string quizid = reader["QuizID"].ToString(); 
         link = "<a href='http://pmv/pssp/StartQuiz.aspx?testid=" + quizid + "'> Click here to participate </a>"; 
         body = @"<b> Please try to participate in the new short safety quiz </b>" 
              + link + 
              @"<br /> <br /> 
         This email was generated using the <a href='http://pmv/pssp/Default.aspx'>PMOD Safety Services Portal </a>. 
         Please do not reply to this email. 
         ";  
        } 
       } 
      } 
      reader.Close(); 
     } 

     using (SqlCommand cmd = new SqlCommand(cmdText2, conn)) 
     { 
      SqlDataReader reader = cmd.ExecuteReader(); 
      if (reader != null) 
      { 
       while (reader.Read()) 
       { 
        string emailTo = reader["Username"].ToString(); 
        string receiverEmail = emailTo + "@gmail.com"; 
        emailAddresses.Add(receiverEmail); 
       } 
      } 
      reader.Close(); 
     } 
     conn.Close(); 
    } 

    foreach (string email in emailAddresses) 
    { 
     SendEmail(email, "", "Notification Email Subject", body, true); 
    } 
} 

回答

1

首先,你的代碼,因爲它目前爲,將只發送一封電子郵件關於最後的測驗。

其次,作爲一般的經驗法則,您應該只檢索數據庫中絕對必要的數據。沒有理由閱讀已經被髮送測驗,這樣你就可以在查詢更改爲:

string cmdText = "SELECT QuizID FROM dbo.QUIZ WHERE IsSent <> 1"; 

第三,你應該更新IsSent爲測驗的郵件已發送後立即每次測驗。

最後,您應該發送一封包含所有收件人的電子郵件作爲BCC用戶,而不是多封電子郵件。

下面是一個包含了所有這些概念的改寫:

protected void SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml) 
    { 
     SmtpClient sc = new SmtpClient("SMTP (MAIL) ADDRESS"); 
     try 
     { 
      MailMessage msg = new MailMessage(); 
      msg.From = new MailAddress("[email protected]", "OUR SYSTEM"); 

      // In case the mail system doesn't like no to recipients. This could be removed 
      msg.To.Add("[email protected]"); 

      msg.Bcc.Add(toAddresses); 
      msg.Subject = MailSubject; 
      msg.Body = MessageBody; 
      msg.IsBodyHtml = isBodyHtml; 
      //Response.Write(msg); 
      sc.Send(msg); 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 

    } 

    protected void SendEmailTOAllUser() 
    { 
     string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspTest;Integrated Security=True"; 

     using (SqlConnection conn = new SqlConnection(connString)) 
     { 
      var sbEmailAddresses = new System.Text.StringBuilder(1000); 
      var quizIds = new List<int>(); 

      // Open DB connection. 
      conn.Open(); 

      string cmdText = "SELECT QuizID FROM dbo.QUIZ WHERE IsSent <> 1"; 
      using (SqlCommand cmd = new SqlCommand(cmdText, conn)) 
      { 
       SqlDataReader reader = cmd.ExecuteReader(); 
       if (reader != null) 
       { 
        while (reader.Read()) 
        { 
         // There is only 1 column, so just retrieve it using the ordinal position 
         quizIds.Add(reader.GetInt32(0)); 
        } 
       } 
       reader.Close(); 
      } 

      string cmdText2 = "SELECT Username FROM dbo.employee"; 
      using (SqlCommand cmd = new SqlCommand(cmdText2, conn)) 
      { 
       SqlDataReader reader = cmd.ExecuteReader(); 
       if (reader != null) 
       { 
        while (reader.Read()) 
        { 
         var sName = reader.GetString(0); 
         if (!string.IsNullOrEmpty(sName) 
         { 
          if (sbEmailAddresses.Length != 0) 
          { 
           sbEmailAddresses.Append(","); 
          } 
          // Just use the ordinal position for the user name since there is only 1 column 
          sbEmailAddresses.Append(sName).Append("@gmail.com"); 
         } 
        } 
       } 
       reader.Close(); 
      } 

      string cmdText3 = "UPDATE dbo.Quiz SET IsSent = 1 WHERE QuizId = @QuizID"; 
      using (SqlCommand cmd = new SqlCommand(cmdText3, conn)) 
      { 
       // Add the parameter to the command 
       var oParameter = cmd.Parameters.Add("@QuizID", SqlDbType.Int); 
       // Get a local copy of the email addresses 
       var sEMailAddresses = sbEmailAddresses.ToString(); 

       foreach (int quizid in quizIds) 
       { 
        string link = "<a href='http://pmv/pssp/StartQuiz.aspx?testid=" + quizid + "'> Click here to participate </a>"; 
        string body = @"<b> Please try to participate in the new short safety quiz </b>" 
             + link + 
             @"<br /> <br /> 
        This email was generated using the <a href='http://pmv/pssp/Default.aspx'>PMOD Safety Services Portal </a>. 
        Please do not reply to this email. 
        "; 

        SendEmail(sEMailAddresses, "", "Notification Email Subject", body, true); 

        // Update the parameter for the current quiz 
        oParameter.Value = quizid; 
        // And execute the command 
        cmd.ExecuteNonQuery(); 
       } 
      } 
      conn.Close(); 
     } 
    } 
+0

感謝您的幫助。我收到了一個錯誤:在郵件頭中發現無效字符:'@',我不知道如何解決它。有任何幫助嗎? – user1093651 2012-01-01 05:18:12

+0

對不起,代碼中有錯誤,我更新了答案。你需要將'if(sbEmailAddresses.Length == 0)'改爲'if(sbEmailAddresses.Length!= 0)'。我還進行了更新,以確保在將數據添加到地址列表之前從數據庫中讀取名稱。 – 2012-01-01 05:50:58

+0

非常感謝您的幫助。我可以弄明白。我在你的代碼中改了一點點。老兄,謝謝。你實際上拯救了我的生命,但現在我面臨着你的代碼的另一個問題。問題是:我想要系統檢查測驗表是否有多於未發送給用戶的測驗。我希望系統只發送這些測驗中的第一個,而不是全部或最後創建的測驗。怎麼做? – user1093651 2012-01-01 06:17:40

1

你需要保持你的QuizIDs的軌道,我建議有一個ArrayList,像這樣:

ArrayList quizIDs = new ArrayList(); 

在你while循環,在那裏你通過閱讀器遍歷並將quizid變量設置爲reader["QuizID"].ToString(),添加以下行以將quizid存儲到列表中:

quizIDs.Add(quizid); 

發送所有電子郵件後,您需要執行查詢,更新所有以前保存的QuizID的IsSent列。

這是你如何建立你的更新查詢:

string updateQuery = "UPDATE dbo.QUIZ SET IsSent = 1 WHERE QuizID in (" + String.Join(",", quizIDs) + ")"; 
相關問題