The purpose of this code is to send emails in the GridView to individuals whose email listed in there, so the code works fine but it does something weird. Let me explain it here, so if my GridView looks like this
ID Name Email
4 Mike Mike@.com
6 John John@.com
9 David David@.com
Once I hit the send button,
- Mike receives all 3 different emails with all the 3 ID’s in the URL starting ID4, ID6, ID9 in the mail message body.
- John receives only a 2 emails starting ID6 and ID9
- David receives only 1 email which is the email for ID9 in mail message body.
What am I doing wrong here? I need each one to receive their respective email only. Can someone help? Note, the DateKeyName in the GridView is “Assigned_To” so I am not sure if I need to change that into “ID”. If I do that then It will throw an error. thanks
Here is the code:
protected void btnSendEmail_Click(object sender, EventArgs e)
{
MailMessage mailMessage = new MailMessage();
foreach (GridViewRow gr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("chkItem");
if (cb.Checked)
{
mailMessage.To.Add(new MailAddress(GridView1.DataKeys[gr.RowIndex]["Assigned_To"].ToString()));
mailMessage.From = new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["fromEmailAddress"]);
mailMessage.Priority = System.Net.Mail.MailPriority.High;
//Text/HTML
mailMessage.IsBodyHtml = false;
string mySubURI = HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("Test.aspx", "ABC.aspx");
mySubURI += String.Format("&ID={0}", gr.Cells[0].Text);
mailMessage.Body = "this is just test... " + " " + Environment.NewLine + mySubURI;
mailMessage.Subject = "Test";
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
try
{
smtpClient.Send(mailMessage);
//Response.Write("<B>Email Has been sent successfully.</B>");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Try creating a new MailMessage after you check the checkbox, what you’re doing now is reusing the same message for each iteration and adding a new mail address without clearing the previous ones.