The specified string is not in the form required for an e-mail address

Total Post:101

Points:709
 2823  View(s)
Ratings:
Rate this:

The specified string is not in the form required for an e-mail address. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: The specified string is not in the form required for an e-mail address.

  1. Post:378

    Points:2694
    Re: The specified string is not in the form required for an e-mail address

    Hi Pravesh, 

    The specified string is not in the form required for an e-mail address

    The problematic code was as follows:

    MailMessage objMsg = new MailMessage(regEmail.Text.ToString(), "me@mysite.com");

    I fixed the issue by replacing that code with this:

    MailMessage objMsg = new MailMessage();

    objMsg.From = new MailAddress(regEmail.Text.ToString());

    objMsg.To.Add(new MailAddress("me@mysite.com"));

    It is also helpful to use a regular expression validator in your user control to make sure the address is valid, you can use the following code for asp:

    <asp:RegularExpressionValidator ID="regex1" ControlToValidate="regEmail" ErrorMessage="Please enter a valid email address" ValidationExpression="^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$" ValidationGroup="regGroup" runat="server" Display="None" SetFocusOnError="True"></asp:RegularExpressionValidator>

    Or if you'd prefer to validate the email in C#

    public static bool IsValidEmail(String Email)
    {
        if( Email != null && Email != "" )
            return Regex.IsMatch(Email, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" );
        else
            return false;
    }

      Modified On Apr-05-2018 04:05:56 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!