Exception: Specified string not in the form required for an email address

Hi,

I’m using Aspose.Words 14.5.0.0 to take a word document and covert it to a .mhtml file. I then am using Aspose.Email 4.1.0 to create an email whose body is the mhtml file and and send to a customer. The email send code is below:

// emailBodyFile = .mhtml file created from Aspose.Words
// multiple email addresses may be delimited by EMAIL_DELIMITER = "$$"
private void SendEmail(string emailFrom, string emailTo, string emailCC, string emailBCC, string subject, string body, string emailBodyFile, List<string> attachments, string host)
{
    string fromEmail = emailFrom;
    string toEmail = emailTo;
    using (Aspose.Email.Mail.MailMessage msg = Aspose.Email.Mail.MailMessage.Load(emailBodyFile))
    {
        msg.From = fromEmail;
        string[] toAddresses = toEmail.Split(new string[] { EMAIL_DELIMITER }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string toAddress in toAddresses)
        {
            msg.To.Add(new Aspose.Email.Mail.MailAddress(toAddress));
        }
        if (!String.IsNullOrEmpty(emailCC))
        {
            string[] ccAddresses = emailCC.Split(new string[] { EMAIL_DELIMITER }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string ccAddress in ccAddresses)
            {
                msg.CC.Add(new Aspose.Email.Mail.MailAddress(ccAddress));
            }
        }
        if (!String.IsNullOrEmpty(emailBCC))
        {
            string[] bccAddresses = emailBCC.Split(new string[] { EMAIL_DELIMITER }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string bccAddress in bccAddresses)
            {
                msg.Bcc.Add(new Aspose.Email.Mail.MailAddress(bccAddress));
            }
        }
        msg.Subject = subject;
        foreach (string attachment in attachments)
        {
            msg.AddAttachment(new Aspose.Email.Mail.Attachment(attachment));
        }
        Aspose.Email.Mail.SmtpClient client = new Aspose.Email.Mail.SmtpClient(host);
        client.Send(msg);
    }
}

In some cases at the highlighted line above we get an exception:

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

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

at œ.š.[1](String data, Int32& offset, String& displayName, Boolean checkAddress)

at Aspose.Email.Mail.MailAddress.[1](String )

at Aspose.Email.Mail.MailAddress.•[1](String )

at MIPS.UserControls.ProposalPopupControl.SendEmail(String emailFrom, String emailTo, String emailCC, String emailBCC, String subject, String body, String emailBodyFile, List`1 attachments, String host)

at MIPS.UserControls.ProposalPopupControl.uxDeliverButton_Click(Object sender, EventArgs e)

As best I can tell, the emails used that produce the error in SendEmail() are valid - there is only one from address and one to address (no bcc or cc). I have also validated that the email address strings are not being corrupted somehow, ie, (no spaces, punctuation OK, no missing @, no missing domain, etc).

To test this further, I created another function to validate the email addresses. I got the basic code off your web site (Programming Email Verification|Documentation):

protected void uxValidateEmailAddress_Click(object sender, EventArgs e)
{
    List<string> addresses = new List<string>();
    addresses.Add("client@druginfo.com");
    addresses.Add("hk1234@columbia.edu");
    Aspose.Email.Verify.EmailValidator ev = new Aspose.Email.Verify.EmailValidator();
    Aspose.Email.Verify.ValidationResult result;
    StringBuilder sb = new StringBuilder();
    if (addresses.Count > 0)
    {
        foreach (string address in addresses)
        {
            ev.Validate(address, out result);
            if (result.ReturnCode == Aspose.Email.Verify.ValidationResponseCode.ValidationSuccess)
            {
                sb.Append(String.Format("[{0}] email address is valid.", address) + "\n");
            }
            else
            {
                sb.Append(String.Format("[{0}] email address is invalid: {1} ", address, result.Message) + "\n");
            }
            ev.Validate(address, Aspose.Email.Verify.ValidationPolicy.SyntaxOnly, out result);
            if (result.ReturnCode == Aspose.Email.Verify.ValidationResponseCode.ValidationSuccess)
            {
                sb.Append(String.Format("SyntaxOnly -> [{0}] email address is valid.", address) + "\n");
            }
            else
            {
                sb.Append(String.Format("SyntaxOnly -> [{0}] email address is invalid: {1} ", address, result.Message) + "\n");
            }
            ev.Validate(address, Aspose.Email.Verify.ValidationPolicy.MailServer, out result);
            if (result.ReturnCode == Aspose.Email.Verify.ValidationResponseCode.ValidationSuccess)
            {
                sb.Append(String.Format("MailServer -> [{0}] email address is valid.", address) + "\n");
            }
            else
            {
                sb.Append(String.Format("MailServer -> [{0}] email address is invalid: {1} ", address, result.Message) + "\n");
            }
            ev.Validate(address, Aspose.Email.Verify.ValidationPolicy.SyntaxAndDomain, out result);
            if (result.ReturnCode == Aspose.Email.Verify.ValidationResponseCode.ValidationSuccess)
            {
                sb.Append(String.Format("SyntaxAndDomain -> [{0}] email address is valid.", address) + "\n");
            }
            else
            {
                sb.Append(String.Format("SyntaxAndDomain -> [{0}] email address is invalid: {1} ", address, result.Message) + "\n");
            }
        }
    }
}

Results are below:

[hk1234@columbia.edu] email address is invalid: Domain error found in the email validation Last Exception: Access denied

SyntaxOnly -> [hk1234@columbia.edu] email address is valid.
MailServer -> [hk1234@columbia.edu] email address is invalid: Domain error found in the email validation Last Exception: Access denied
SyntaxAndDomain -> [hk1234@columbia.edu] email address is invalid: Domain error found in the email validation Last Exception: Access denied

[client@druginfo.com] email address is invalid: Domain error found in the email validation Last Exception: Access denied
SyntaxOnly -> [client@druginfo.com] email address is valid.
MailServer -> [client@druginfo.com] email address is invalid: Domain error found in the email validation Last Exception: Access denied
SyntaxAndDomain -> [client@druginfo.com] email address is invalid: Domain error found in the email validation Last Exception: Access denied

Based on the validation tests, the email addresses are valid syntax, but domain/mail server validation fails. I guess my question is, in the first code block where I’m sending .mhtl based emails, why do some email addresses work and others that are apparently valid, do not? Are you guys doing additional domain/mail server checks in client.Send(msg); that would cause an email address exception?

Unfortunately, the failing email addresses always occur with client emails so we really don’t have a test email address that fails.

Thanks,
Scott

Hi Scott,


Thank you for writing to Aspose support team.

When the ev.Validate(address, out result) is invoked, you are actually validating the address with ValidationPolicy.MailServer option i.e. validating the email address by trying to connect to the mail server. If there is something wrong with the server such as access issues, it will raise exception. Also, if a username/email doesn’t exist e.g. abc@gmail.com, the the ValidationPolicy.MailServer will raise an exception.

If you want to validate only the syntax of the email address, you may use ValidationPolicy.SyntaxOnly option.

If the issue still persists with the original email addresses, I would request you to please provide us with a test account credentials and some valid email addresses to further investigate this issue at our end.

Hi Kashif,

Thanks for the reply.
My main issue is with sending email and getting an exception about invalid email address (see first part of my original post).
I only included the validation code as proof that there was nothing wrong with the email address syntax of the To; address.
Could you explain what may be happening when I call client.Send(msg) where the email addresses are all valid, but I still get an exception when trying to send an email?
Is it possible that the extensive validation (by connecting to the mail server) is also happening when sending email? If so, is there a way to minimize this validation?
We don’t need all this extensive error checking when sending email. All we want is to send the email to the address we have on file and let the mail servers do the job of rejecting or delivering the email.
Thanks,
Scott

Kashif,

Simple example is this:
From address -> client@druginfo.com
To address -> hk1234@columbia.edu
Sending this email using Aspose.Email in my original post throws exception:
The specified string is not in the form required for an e-mail address.

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

at œ.š.[1](String data, Int32& offset, String& displayName, Boolean checkAddress)

at Aspose.Email.Mail.MailAddress.1

at Aspose.Email.Mail.MailAddress.•1

at MIPS.UserControls.ProposalPopupControl.SendEmail(String emailFrom, String emailTo, String emailCC, String emailBCC, String subject, String body, String emailBodyFile, List`1 attachments, String host)

at MIPS.UserControls.ProposalPopupControl.uxDeliverButton_Click(Object sender, EventArgs e)

Why is this exception happening? The email addresses have valid syntax.

Thanks,

Scott

Hi Scott,


We are working on this issue and request you to spare us little time to complete the analysis. I will write back here soon to share the feedback in this regard.

Your patience and understanding is appreciated here.

Hi Scott,

I have tested the sample email account shared by you and sent a test email to hk1234@columbia however no exception is raised and message is sent successfully. Although the server sends “Delivery Status Notification (Failure)” but no issue is observed while sending message.

Could you please test the following code using latest release Aspose.Email for .NET 4.7.0 and let us know the feedback?

static void Email582618()
{
GetSmtpClient().Send(new MailMessage("mytestaccount@gmail.com", “hk1234@columbia.edu”, “Subject”, “Body”));
}

static SmtpClient GetSmtpClient()
{
SmtpClient client = new SmtpClient();
client.Host = “[smtp.gmail.com](http://smtp.gmail.com/)”;
client.Username = “mytestaccount”;
client.Password = “password”;
client.Port = 587;
client.SecurityOptions = SecurityOptions.SSLExplicit;
return client;
}

Kashif,

Sorry for the delay - I got pulled off on other things.

I added your sample code to our app. I have it wired up to execute when a link button is clicked.

After clicking the link, the page sits for 2 minutes and the following error below is displayed.

I’m not sure what this code is proving since it’s not how I invoke sending an email in our app. I don’t want to get bogged down in debugging this sample code if possible.

Let’s suspend your involvement on this for now - I will begin using the Aspose.Email 4.7.0 version and double check my code for any potential errors. If I still see the “System.FormatException: The specified string is not in the form required for an e-mail address.” exception for apparently valid email addresses after a few weeks of using 4.7.0, I’ll reply to this post or open another one.

Server Error in ‘/’ Application.

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.29.108:587

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.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.29.108:587

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.29.108:587]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +273
System.Net.Sockets.Socket.Connect(EndPoint remoteEP) +162
œ..a(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address,  state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +489

[IOException: ConnectFailure]
.‡.Initialize(String , Int32 ) +1019
.šŸ.ƒ() +380
œ.ƒ.‚‡() +975
Aspose.Email.Mail.™•™.››(Object ) +588

[SmtpException: Failure sending mail.]
Aspose.Email.Mail.SmtpClient.BulkSend(IEnumerator messages) +733
PPD.MIPS.Admin.DefaultPage.uxSendTestEmail_Click(Object sender, EventArgs e) in c:\Projects\MITAWeb2012\MITAWeb2012\Admin\Default.aspx.cs:177
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +153
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804



Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

Hi Scott,


Thank you for sharing your feedback. Please feel free to contact us on Aspose.Email forum after you are done with your findings. We’ll look into it for assisting you further.