Search code examples
c#asp.netsmtphtml-emailmailmessage

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


Trying to send email to multiple recipient using below code gives me this error:

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

string[] email = {"[email protected]","[email protected]"};
using (MailMessage mm = new MailMessage("[email protected]", email.ToString()))
{
     try
     {
          mm.Subject = "sub;
          mm.Body = "msg";
          mm.Body += GetGridviewData(GridView1);
          mm.IsBodyHtml = true;
          SmtpClient smtp = new SmtpClient();
          smtp.Host = "smtpout.server.net";
          smtp.EnableSsl = false;
          NetworkCredential NetworkCred = new NetworkCredential("email", "pass");
          smtp.UseDefaultCredentials = true;
          smtp.Credentials = NetworkCred;
          smtp.Port = 80;
          smtp.Send(mm);
          ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
      }
      catch (Exception ex)
      {
          Response.Write("Could not send the e-mail - error: " + ex.Message);    
      }
}

Solution

  • Change your using line to this:

    using (MailMessage mm = new MailMessage())
    

    Add the from address:

    mm.From = new MailAddress("[email protected]");
    

    You can loop through your string array of e-mail addresses and add them one by one like this:

    string[] email = { "[email protected]", "[email protected]", "[email protected]" };
    
    foreach (string address in email)
    {
        mm.To.Add(address);
    }
    

    Example:

    string[] email = { "[email protected]", "[email protected]", "[email protected]" };
    
    using (MailMessage mm = new MailMessage())
    {
        try
        {
            mm.From = new MailAddress("[email protected]");
    
            foreach (string address in email)
            {
                mm.To.Add(address);
            }
    
            mm.Subject = "sub;
            // Other Properties Here
        }
       catch (Exception ex)
       {
           Response.Write("Could not send the e-mail - error: " + ex.Message);
       }
    }