Question

Currently when my program reads the specific table and sends Emails out to 8 users if there is 8 users there should receive one email. It should only send one email out per user. Not 8 emails per user. This is my code:

        comm.CommandText = "SELECT * FROM tblRent WHERE DateIn < " + ImorgenTicks + " AND Status = 'Out' AND Trainee IS NULL";

        SqlDataReader read = comm.ExecuteReader();
        if (read.HasRows)
        {
            while (read.Read())
            {
                string mail = read["Mail"].ToString();
                try
                {
                     message.To.Add(mail);
                    //email
                    smtp.Send(message);
                }
                catch
                {
                    MessageBox.Show("Text");
                } 

            } 
        } 

I've searched the internet and found some solution and haven't got them to work.

Était-ce utile?

La solution

It seems you are adding multiple addresses to the same MailMessage on each iteration. You need to clear the message.To collection or create a new message in each iteration

while (read.Read())
{
    string mail = read["Mail"].ToString();
    try
    {
        message.To.Clear();
        message.To.Add(mail);

        //email    
        smtp.Send(message);
    }
    catch
    {
        MessageBox.Show("Text");
    } 
} 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top