Dynamic email list using sql table for recipient

I’m looking to send multiple emails from a c# console app using a sql table column as the source for my list.

With the following code i’m getting an error “System.FormatException: ‘The specified string is not in the form required for an e-mail address.'”

When I send the output to console all that is passing to var m is the first letter of the string.

I’m very close to having this work as this looks like the last piece.

Could anyone please point me in the direction to get this to work.

        con = new SqlConnection("MyConnectionString");

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "SELECT * FROM UserEmails";
        cmd.Connection = con;

        try
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {

                MailMessage mailMessage = new MailMessage();

                //string[] to = { "[email protected]", "[email protected]"}; //<-- this works 

                string to = reader.GetString(1);   //<-- this dosent work :( 

                foreach (var m in to)
                {
                    mailMessage.To.Add(m);
                }

                mailMessage.Subject = "Hello";
                mailMessage.Body = "This is a test email";
                mailMessage.From = new MailAddress("[email protected]", "me");

                SmtpClient smtpMail = new SmtpClient();
                smtpMail.Host = "smtp.gmail.com";
                smtpMail.Credentials = new NetworkCredential("[email protected]", "password");
                smtpMail.EnableSsl = true;

                try
                {
                    smtpMail.Send(mailMessage);
                    Console.WriteLine("Message Sent");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message.ToString());
                }
            }
            reader.Close();
        }
        finally
        {
            con.Close();
        }

Answer

Your iterating through the characters of to, which is a string.

Instead of this:

foreach (var m in to)
{
  mailMessage.To.Add(m);
}

Do this:

mailMessage.To.Add(new MailAddress(to));

Leave a Reply

Your email address will not be published. Required fields are marked *