Search code examples
c#asp.netlistmailmessage

Unable to attach email to MailMessage


I am trying to generate a list of emails from sql then use that list to attach each email address to a mail message. I am getting:

The specified string is not in the form required for an e-mail address.

What am I doing wrong? This error is happening at the foreach within the Page_Load. When looking at the mailAddress variable it is showing the email addresses normally as it should "[email protected]"

I've tried a few suggestions like changing the mail add to:

msg.To.Add(new MailAddress(mailAddress.ToString())); 

but that didn't work.

public class Supervisor
{
   public string Email { get; set; }
}

public List<Supervisor> LoadSupervisors(int ID)
{
   var listOfEmails = new List<Supervisor>();
   using (SqlConnection conn = new SqlConnection(""))
   {
      SqlCommand cmd = new SqlCommand(@"", conn2);
      cmd.Parameters.AddWithValue("@ID", ID);
      conn.Open();
      SqlDataReader rdr = cmd.ExecuteReader();
      while (rdr.Read())
      {
         var supervisor = new Supervisor();
         supervisor.Email = rdr["Email"].ToString();
         listOfEmails.Add(supervisor);
      }
    }
    return listOfEmails;
}

protected void Page_Load(object sender, EventArgs e)
{
   //----- Bunch of code that isn't related
   while (rdr.Read())
   {
      var listOfEmails = new List<Supervisor>();
      listOfEmails = LoadSupervisors(Convert.ToInt32(rdr["UserID"]));

      MailMessage msg = new MailMessage();
      SmtpClient server = new SmtpClient("");
      foreach (var mailAddress in listOfEmails)
      {
          msg.To.Add(mailAddress.ToString());
      }
      //----- Bunch of code that isn't related
   }
}

Solution

  • I think you should get .Email property of your mailAddress instead of itself. Because mailAddress is a Supervisor, not a string or something.

    Try as;

    msg.To.Add(mailAddress.Email.ToString());
    

    But of course, we don't know anything about Email type, I assume it returns this mail address as a string since you said you see it on debugger or something.