指定的字符串不是电子邮件地址所需的格式。发送电子邮件时

时间:2015-09-01 12:26:24

标签: c# asp.net smtp html-email mailmessage

尝试使用以下代码向多个收件人发送电子邮件时出现此错误:

  

指定的字符串不是电子邮件所需的格式   地址。

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);    
      }
}

3 个答案:

答案 0 :(得分:5)

将使用行更改为:

using (MailMessage mm = new MailMessage())

添加发件人地址:

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

您可以循环遍历您的字符串数组的电子邮件地址,并逐个添加它们:

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

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

示例:

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);
   }
}

答案 1 :(得分:0)

目前您的代码:

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

"email"视为电子邮件地址,最终不是电子邮件地址,而是包含电子邮件地址的字符串数组。

所以你可以尝试这样:

foreach (string add in email)
{
    mm.To.Add(new MailAddress(add));
}

答案 2 :(得分:0)

在使用SMTP.js时遇到了这个问题,但是问题来自空格,因此在使用电子邮件时请尝试将其修剪掉。我希望这对某人有帮助。