1

I am trying to send an email to the user's account when the user clicks send button. But I am getting the above error. Below is my sendClick code.

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

Stack Trace

[FormatException: The specified string is not in the form required for an e-mail address.]
System.Net.Mail.MailAddressParser.ReadCfwsAndThrowIfIncomplete(String data, Int32 index) +1475945
System.Net.Mail.MailAddressParser.ParseDomain(String data, Int32& index) +135 System.Net.Mail.MailAddressParser.ParseAddress(String data, Boolean expectMultipleAddresses, Int32& index) +99
System.Net.Mail.MailAddressParser.ParseAddress(String data) +23
System.Net.Mail.MailAddress..ctor(String address, String displayName, Encoding displayNameEncoding) +220
System.Net.Mail.MailMessage..ctor() +130
events.btnsendCode_Click(Object sender, EventArgs e) in d:\inetpub\vhosts\marpallichande.in\httpdocs\Test\events.aspx.cs:101
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9552874
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String 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

Which part I am committing mistake and need to correct it?

Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
  • If you look at the stack trace when you get the exception.... probably we could have a better idea. – Steve Dec 07 '13 at 13:42
  • @Steve. Ok I will jus add the stack trace in the ques.. – Guruprasad J Rao Dec 07 '13 at 13:44
  • Are you sure the txtemail variable is passing a valid email address? – mosesfetters Dec 07 '13 at 13:47
  • The error seems to be orginated by the constructor of the first MailAddress object. But what is the email typed in the textbox? – Steve Dec 07 '13 at 13:47
  • @Steve.. the email is kshkrao3@gmail.com – Guruprasad J Rao Dec 07 '13 at 13:51
  • 2
    Maybe try hard coding the to and from email addresses to a gmail account you own to see if that works and go from there? – mosesfetters Dec 07 '13 at 14:03
  • @FettMo.. Will check it. – Guruprasad J Rao Dec 07 '13 at 14:08
  • Could it be that 'txtemail.Text.ToString()' returns something different than 'txtemail.Text'? Try removing the '.Tostring()'. – Vegard Dec 07 '13 at 14:08
  • @Vegard.. It was the same at the begining and even then I got the error so tried this way around., but still getting error. – Guruprasad J Rao Dec 07 '13 at 14:10
  • 1
    I suggest you to use the debugger and put a breakpoint on the construction of the first MailAddress. Then proceed step by step examining all the input passed to the two MailAddress until you hit the exception. – Steve Dec 07 '13 at 14:20
  • @Steve.. The same code works well and fine in my localhost. Now that I have uploaded it to the server, I am getting error. How to check it in the domain. – Guruprasad J Rao Dec 07 '13 at 15:14
  • Difficult to help you on this scenario. Check the solutions and possible errors proposed in this link http://social.msdn.microsoft.com/Forums/en-US/326c0c05-d833-4bae-8f64-b3738cfb2e8c/the-specified-string-is-not-in-the-form-required-for-an-email-address?forum=netfxnetcom – Steve Dec 07 '13 at 15:46

2 Answers2

14

The reason it fails is using the empty constructor without the mail settings to match:

MailMessage mm = new MailMessage();

The empty constructor relies on:

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

in your app or web.config file. So either use the constructor that expects a from and to address, or add that node to your app/web.config file.

I firmly believe this is a bug in the .Net framework, because we were able to create new MailMessage() objects and then assign the "from" later on, but in .Net 4.0 and under certain conditions—which I still don't fully understand—this fails. I welcome being corrected of course, but for now, this seems like an oversight.

So some of our customers never encountered this issue, but to fix it we had to add that dummy setting to the web.config files.

Michael
  • 8,362
  • 6
  • 61
  • 88
reckface
  • 5,678
  • 4
  • 36
  • 62
  • I have included this set ups but still It was not working. Then I came to know about second step verification in Gmail set up which later worked for me. Thank you for the information btw. – Guruprasad J Rao Feb 06 '14 at 04:15
1

I had a similar problem with getting [FormatException: The specified string is not in the form required for an e-mail address.] too. My problem was with this code:

  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){...}

As you can see I just tried and caught only sending part. But this problem was thrown from MailMessage constructor. I would have never guessed that a constructor would throw an exception. So I just tried this code independently:

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

The result of this code is [FormatException: The specified string is not in the form required for an e-mail address.]. If you try this:

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

you'll get ArgumentException: The parameter 'from'(or 'to') cannot be an empty string.

So what you need to do in these kind of cases is you include the MailMessage construction part in the try catch block too and make sure that the exception you catch covers exception types that MailMessage constructor might throw, in this particular case, FormatException. Although I hate cathcing the Exception class, in this case it seems to be a perfect fit.

Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206