Jason F
Jason F

Reputation: 31

SmtpClient.Send failing with System.FormatException: Smtp server returned an invalid response

I am trying to use the following code to send an email:

//create the mail message
MailMessage mail = new MailMessage(from, to);

//set the content
mail.Subject = "This is a test email";
mail.Body = "this is the body content of the email.";

//send the message
string server = "smtp01.xyz.net";
SmtpClient smtp = new SmtpClient(server);
smtp.Credentials = new NetworkCredential(username, password); 
smtp.EnableSsl = enablessl;
try
{
    smtp.Send(mail);
}
catch (Exception ex)
{
    Exception ex2 = ex;
    string errorMessage = string.Empty;
    while (ex2 != null)
    {
        errorMessage += ex2.ToString();
        ex2 = ex2.InnerException;
    }
    Console.WriteLine(errorMessage);
}

The resulting stack trace is:

System.Net.Mail.SmtpException: Failure sending mail. ---> System.FormatException: Smtp server returned an invalid response.
   at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
   at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
   at System.Net.Mail.ReadLinesCommand.Send(SmtpConnection conn)
   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)

If I telnet to the server on port 25 the response is:

220 smtp01.xyz.net ESMTP Postfix
EHLO test.com
250-smtp01.xyz.net
250-STARTTLS
250-SIZE 30000000
250-VRFY
250-ETRN
250-AUTH PLAIN LOGIN
250-AUTH=PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN

I have tried with both EnableSsl set and not set.

I don't understand what it is about the response that it thinks is invalid?

Upvotes: 2

Views: 7880

Answers (2)

user1387916
user1387916

Reputation: 229

I had this issue and it was due to specifying a server name that began with mail instead of mailbox. This error threw me off because even though the SMTP server specified was the source of the problem, the construction of the SmtpClient did not throw an exception the way it did with a couple of other servers I tried. The error message makes it seem like it is a problem with what you are sending but at least in my case, it was the specified SMTP server.

Upvotes: 0

mreyeros
mreyeros

Reputation: 4379

Are you by any chance using ASP.net MVC? If so make sure that your server SMTP server settings are declared/defined in the correct web.config at the root of the application and not in the web.config that is located in the Views folder.

Upvotes: 1

Related Questions