5

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 = {"emailone@gmail.com","emailtow@gmail.com"};
using (MailMessage mm = new MailMessage("teset123321@gmail.com", 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);    
      }
}
jack
  • 75
  • 1
  • 1
  • 4
  • 1
    new NetworkCredential("email@mymail.com", "pass"); – sujith karivelil Sep 01 '15 at 12:27
  • Before asking a question, make sure you've thoroughly debugged your program by stepping through the code and trying to spot what the problem might be. And when you posted a question, make sure you specify exactly which line your error is coming from – mason Sep 01 '15 at 13:13

3 Answers3

6

Change your using line to this:

using (MailMessage mm = new MailMessage())

Add the from address:

mm.From = new MailAddress("myaddress@gmail.com");

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

string[] email = { "emailone@gmail.com", "emailtwo@gmail.com", "emailthree@gmail.com" };

foreach (string address in email)
{
    mm.To.Add(address);
}

Example:

string[] email = { "emailone@gmail.com", "emailtwo@gmail.com", "emailthree@gmail.com" };

using (MailMessage mm = new MailMessage())
{
    try
    {
        mm.From = new MailAddress("myaddress@gmail.com");

        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);
   }
}
Equalsk
  • 7,954
  • 2
  • 41
  • 67
1

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));
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

I was having this issue while working with SMTP.js but the issues were coming from the whitespace so please try and trim it off when working with emails. I hope this helps someone.