0

I have a gridview showing data containing Name, Email, Date etc for customers from SQL table. It contains checkboxes to select all rows. On click of header checkbox the checkboxes in rows are also being checked(Its working fine). Code for gridview binding:

private void BindGrid()
        {
            using (var db = new DatabaseHelper())
            {
                using (var ds = db.ExecDataSet(Queries.BindReminderEmailGrid))
                {
                   Grid.DataSource = ds;
                }
            }
            Grid.DataBind();
        }

calling this code inside if(!IsPostBack){} on PageLoad.

I have a button on click of that i am sending emails to all checked rows:

protected void btnSendEmailToAll_Click(object sender, EventArgs e)
        {
            string Name = "";
            string username = Master.User;               

            CheckBox ChkBoxHeader = (CheckBox)Grid.HeaderRow.FindControl("chkboxSelectAll");

            //Create a temporary DataTable
            DataTable dtCustomers = new DataTable();
            dtCustomers.Columns.AddRange(new DataColumn[3] { new DataColumn("name", typeof(string)),
                        new DataColumn("email",typeof(string)), new DataColumn("EmailSentOn",typeof(string)) });

            //Copy the Checked Rows to DataTable
            foreach (GridViewRow row in Grid.Rows)
            {
                // Only look in data rows, ignore header and footer rows
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow");

                    if (ChkBoxHeader.Checked == true)
                    {
                        ChkBoxRows.Checked = true;
                    }
                    if (ChkBoxRows.Checked == true)
                    {
                        Name = (row.FindControl("lblname") as Label).Text.ToLower();                            

                        dtCustomers.Rows.Add(Name, (row.FindControl("lblemail") as Label).Text, (row.FindControl("lblEmailsentOn") as Label).Text);

                        var id = Grid.DataKeys[row.RowIndex].Value;
                        using (var db = new DatabaseHelper())
                        {
                            db.ExecNonQuery(Queries.UpdateReminderEmailSentData, "@RW", id);
                        }
                    }
                }
            }

            string subject = "Email Subject";

            //Using Parallel Multi-Threading send multiple bulk email.
            Parallel.ForEach(dtCustomers.AsEnumerable(), row =>
            {
                string body = this.PopulateBody(Name, row["EmailSentOn"].ToString(), username);
                SendHtmlFormattedEmail(row["email"].ToString(), subject, body.ToString());
            });

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Email Sent Successfully')", true);
            BindGrid();
        }

SendHTMLFormatedEmail Function:

 private void SendHtmlFormattedEmail(string recepientEmail, string subject, string ShowBody)
        {
            if (recepientEmail != "")
            {
                var smtp = new SmtpClient()
                {
                    Host = WebConfigurationManager.AppSettings["Host"],
                    EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"]),                    
                    UseDefaultCredentials = true,
                    Credentials = new System.Net.NetworkCredential(WebConfigurationManager.AppSettings["UserName"], WebConfigurationManager.AppSettings["Password"]),
                    Port = int.Parse(WebConfigurationManager.AppSettings["Port"])
                };

                 using (MailMessage mailMessage = new MailMessage())
                    {
                        mailMessage.From = new MailAddress(WebConfigurationManager.AppSettings["UserName"], "Email From Us");
                        mailMessage.Subject = subject;
                        mailMessage.Body = ShowBody;

                        mailMessage.IsBodyHtml = true;
                        mailMessage.To.Add(new MailAddress(recepientEmail));

                     smtp.Send(mailMessage);
                    }

            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please enter a valid email address')", true);
            }
        }

Everything seems working fine, but the problem is that it only send email to few customers. For example today i send emails to around 56 customers but only 11 emails actually been send.

After editing I got following error:

Service not available, closing transmission channel. The server response was: 4.7.0 Temporary System Problem. Try again later (WS). x4sm1307841pfb.101 - gsmtp

And send email to 12 customers only but with same name:(

I am not able to track it whats going wrong. Please help me how it can be fixed. Thanks in advance..!!

Preet
  • 984
  • 2
  • 14
  • 34
  • 1
    Why are you spawning **another** thread inside `SendHtmlFormattedEmail` when the caller is the result of `Parallel.ForEach()`? It's not as if the rest of your code is doing much –  Sep 08 '17 at 03:21
  • Should i remove that thread? – Preet Sep 08 '17 at 03:42
  • @MickyD is on the money (and should probably post the comment as an answer). You're using TPL and Threading. Use one or the other. Personally I would remove the Threading and use the `Parallel.ForEach` – Jeremy Thompson Sep 08 '17 at 03:50
  • after removing that got following error: Service not available, closing transmission channel. The server response was: 4.7.0 Temporary System Problem. Try again later (WS). x4sm1307841pfb.101 - gsmtp – Preet Sep 08 '17 at 03:56

0 Answers0