I am making an windows form application in c#, it has to be able to send an email to all the recipient ids that are in a table in an Access Database.
I already understand how to send the mails and even successfully made tests, but I don't understand how to convert column the has all de email ids to a comma separated string.
I am also kinda confused if this code goes inside the forms code or somewhere else.
I already tried using foreach loops and for some reason they have errors saying that i cannot use them.
I have also read a bit of linq but i could not understand where to even implement such code in my program.
Here is the code for the email sending button:
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtpserver = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected],[email protected]");
mail.Subject = "Que xopa";
mail.Body = "probando 1 2 3";
smtpserver.Port = 587;
smtpserver.Credentials = new
System.Net.NetworkCredential("[email protected]","proyectofinal69lus");
smtpserver.EnableSsl = true;
smtpserver.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
For now I have achieved sending mail to the accounts seen in the code, so that works, what I need is the accounts in the database to be in a separated comma string format so I can use them in this button.
It is unclear why you would not simply query the database for this info. However, if you already have the DataTable
then, as others have pointed out, you will need to loop through the DataTable.Rows
collection and grab the email address cell from that row, add a comma, then continue this for all the rows in the table. A StringBuilder
may be helpful for building this comma delimited email string. It may look something like below…
private string GetEmailAddress(DataTable dt) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dt.Rows.Count; i++) {
sb.Append(dt.Rows[i]["Email"].ToString());
if (i < dt.Rows.Count - 1)
sb.Append(",");
}
sb.AppendLine();
return sb.ToString();
}