Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);    
      }
}
like image 261
jack Avatar asked Sep 01 '15 12:09

jack


2 Answers

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);
   }
}
like image 115
Equalsk Avatar answered Oct 24 '22 09:10

Equalsk


Presently your code:

new NetworkCredential("email", "pass");

treats "email" as an email address which eventually is not an email address rather a string array which contains the email address.

So you can try like this:

foreach (string add in email)
{
    mm.To.Add(new MailAddress(add));
}
like image 43
Rahul Tripathi Avatar answered Oct 24 '22 11:10

Rahul Tripathi