Как отправить письмо всем в таблице с помощью SqlDataReader - PullRequest
0 голосов
/ 22 апреля 2020

Я использую код для отправки электронной почты всем в таблице {table_name (id, email, username)}}, но этот код отправляет почту только на первое электронное письмо в таблице.

public void Sendmail()
        {
            SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
            con1.Open();
            SqlCommand cmd1 = new SqlCommand("select * from table_name", con1);
            SqlDataReader dr = cmd1.ExecuteReader();
            if (dr.Read())
            {
                string useremail = dr["email"].ToString(); //i assume this is the problem not sure
                string username = dr["username"].ToString(); //i assume this is the problem not sure
                var mm = new MailMessage
                {
                    From = new MailAddress("testerforeverything@gmail.com", "bot"),
                    Subject = sub.Text,
                    Body = string.Format("hello,Subscriber<br/>{0}<h3>This is bot<h3>", body.Text),
                    IsBodyHtml = true
                };
                while (dr.Read())
                {
                    var to = new MailAddress(useremail, username);
                    mm.To.Add(to);
                }
                //MailMessage mm = new MailMessage("testerforeverything@gmail.com",useremail)
                //{
                //    Subject = sub.Text,
                //    Body = string.Format("hello,Subscriber<br/>{0}<h3>This is bot.<h3>", body.Text),
                //    IsBodyHtml = true
                //};
                //var datatable = new DataTable();
                //var numberofrows = datatable.Rows.Count;
                //for (int i = 0; i < numberofrows; i++)
                //{
                //    useremail = (string)datatable.Rows[i]["email"];
                //    mm.To.Add(new MailAddress(useremail));
                //}
                SmtpClient smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    EnableSsl = true
                };
                NetworkCredential nc = new NetworkCredential
                {
                    UserName = "testerforeverything@gmail.com",
                    Password = "password"
                };
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = nc;
                smtp.Port = 587;
                smtp.Send(mm);
                con1.Close();
                Response.Redirect(Request.RawUrl);
            }
        }

и ранее я Использовал закомментированный код, который не имеет значения, пожалуйста, помогите. спасибо.

1 Ответ

1 голос
/ 22 апреля 2020
  1. Вы используете SqlDataReader неправильно. Пожалуйста, прочитайте этот пост .
  2. Вы должны переместить объект SmtpClient из l oop.
  3. Response.Redirect (Request.RawUrl); должно быть после l oop.

Вот фиксированный код.

 public void Sendmail()
    {
        SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
        con1.Open();
        SqlCommand cmd1 = new SqlCommand("select * from table_name", con1);
        SqlDataReader dr = cmd1.ExecuteReader();

        SmtpClient smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                EnableSsl = true
            };
            NetworkCredential nc = new NetworkCredential
            {
                UserName = "testerforeverything@gmail.com",
                Password = "password"
            };
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = nc;
            smtp.Port = 587;

        while (dr.Read())
        {
            string useremail = dr["email"].ToString(); //i assume this is the problem not sure
            string username = dr["username"].ToString(); //i assume this is the problem not sure
            var mm = new MailMessage
            {
                From = new MailAddress("testerforeverything01@gmail.com", "bot"),
                Subject = sub.Text,
                Body = string.Format("hello,Subscriber<br/>{0}<h3>Team makes IELTS simple<h3>", body.Text),
                IsBodyHtml = true
            };

            var to = new MailAddress(useremail, username);
            mm.To.Add(to);

            smtp.Send(mm);                
        }
        con1.Close();
        Response.Redirect(Request.RawUrl);
    }
...