应用程序错误:指定的字符串不是电子邮件地址所需的格式

时间:2013-12-07 13:36:42

标签: asp.net c#-4.0 smtp

我正在尝试在用户点击发送按钮时向用户的帐户发送电子邮件。但我得到了上述错误。以下是我的 sendClick 代码。

protected void btnsendCode_Click(object sender, EventArgs e)
{
    try
    {
        if (txtemail.Text != "")
        {
            Random rd = new Random();

            veri = rd.Next(1000, 10000);
            MailMessage mm = new MailMessage();
            mm.To.Add(new MailAddress(txtemail.Text.ToString()));

            mm.From = new MailAddress("xxx@yyy.in", "Verification Mail");
            mm.Body = "Your Verification Code is - " + veri.ToString();
            mm.IsBodyHtml = true;
            mm.Subject = "Verification mail";
            SmtpClient smcl = new SmtpClient();
            smcl.Host = "smtp.gmail.com";
            smcl.Port = 587;
            smcl.Credentials = new NetworkCredential("xxx@yyy.in", "xxx");
            //smcl.EnableSsl = true;
            smcl.Send(mm);
            Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Verification Code sent to your Email ID! Please Check your Email!!');", true);
            txtverify.Enabled = true;
            btnsendCode.Text = "Send Code Again";
            lblmsg.Visible = false;
        }
        else
        {
            lblmsg.Visible = true;
            lblmsg.Text = "Please enter Email ID!!";
            lblmsg.ForeColor = System.Drawing.Color.Yellow;
            lblmsg.BorderColor = System.Drawing.Color.Red;
            lblmsg.BorderStyle = BorderStyle.Ridge;
            lblmsg.BorderWidth = new Unit("2");
            lblmsg.Focus();
        }
    }
    catch (WebException we)
    {
        lblmsg.Visible = true;
        lblmsg.Text = we.Message.ToString();
        lblmsg.ForeColor = System.Drawing.Color.Yellow;
        lblmsg.BorderColor = System.Drawing.Color.Red;
        lblmsg.BorderStyle = BorderStyle.Ridge;
        lblmsg.BorderWidth = new Unit("2");
    }
}

堆栈跟踪

  

[FormatException:指定的字符串不是所需的格式   电子邮件地址。]
  System.Net.Mail.MailAddressParser.ReadCfwsAndThrowIfIncomplete(字符串   数据,Int32指数)+1475945
  System.Net.Mail.MailAddressParser.ParseDomain(String data,Int32&   index)+135 System.Net.Mail.MailAddressParser.ParseAddress(String   data,Boolean expectMultipleAddresses,Int32&指数)+99
  System.Net.Mail.MailAddressParser.ParseAddress(String data)+23
  System.Net.Mail.MailAddress..ctor(String address,String displayName,   编码displayNameEncoding)+220
  System.Net.Mail.MailMessage..ctor()+130
  events.btnsendCode_Click(Object sender,EventArgs e)in   d:\的Inetpub \虚拟主机\ marpallichande.in \的httpdocs \测试\ events.aspx.cs:101
  System.Web.UI.WebControls.Button.OnClick(EventArgs e)+9552874
  System.Web.UI.WebControls.Button.RaisePostBackEvent(字符串   eventArgument)+103
  System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(字符串   eventArgument)+10
  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler   sourceControl,String eventArgument)+13
  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)   +35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint)   1724

我犯了哪个错误,需要纠正它?

2 个答案:

答案 0 :(得分:10)

失败的原因是使用没有邮件设置的空构造函数来匹配:

MailMessage mm = new MailMessage();

空构造函数依赖于:

  <system.net>
    <mailSettings>
      <smtp from="report@company.com" />
    </mailSettings>
  </system.net>

在您的应用或web.config文件中。因此,要么使用需要from和to的地址的构造函数,要么将该节点添加到app / web.config文件中。

I firmly believe this是.Net框架中的一个错误,因为我们能够创建新的MailMessage()对象,然后在以后分配,但在.Net 4.0中,在某些条件下,我仍然没有完全明白这个失败了。我当然欢迎纠正,但就目前而言,这似乎是一种疏忽。

因此我们的一些客户从未遇到过此问题,但为了解决这个问题,我们必须将该虚拟设置添加到web.config文件中。

答案 1 :(得分:1)

我也遇到类似的问题[FormatException: The specified string is not in the form required for an e-mail address.]。我的问题出在这个代码上:

  void SendMail(string destinationEmail)
    MailMessage message=new MailMessage("mytestmail@test.com",destinationEmail);
    SmtpClient mailClient = new SmtpClient("mail.test.com", 587);
    mailClient.Credentials = new System.Net.NetworkCredential("mytestmail", "pswd");
    try{
     mailClient.Send(mail);
    }
    catch (Exception ex){...}

正如你所看到的那样,我只是试着发现只发送了一部分。但是这个问题是从MailMessage构造函数抛出的。我永远不会猜到构造函数会抛出异常。所以我只是独立尝试了这个代码:

MailMessage mail = new MailMessage("test", "test");

此代码的结果为[FormatException: The specified string is not in the form required for an e-mail address.]。如果你试试这个:

MailMessage mail = new MailMessage("", "");    

您将获得ArgumentException:The parameter 'from'(or 'to') cannot be an empty string.

因此,在这种情况下您需要做的是在try catch块中包含MailMessage构造部分,并确保您捕获的异常涵盖了MailMessage构造函数可能抛出的异常类型,在此特定情况下,FormatException 。虽然我讨厌隐藏Exception类,但在这种情况下,它似乎是一个完美的契合。