ZP Baloch
ZP Baloch

Reputation: 391

SmtpClient.Send() taking long and timout on server

I am using this code to send and email.

StringBuilder Emailbody = new StringBuilder();
                    Emailbody.Append("Hello World!");
                    MailMessage mail = new MailMessage();
                    mail.To.Add("[email protected]");
                    mail.From = new MailAddress("[email protected]");
                    mail.Subject = " MaxRemind User PIN Code";
                    mail.Body = Emailbody.ToString();
                    mail.IsBodyHtml = true;
                    SmtpClient smtpClient = new SmtpClient();
                    smtpClient.Host = "smtpout.secureserver.net";
                    smtpClient.Port = 25;
                    smtpClient.EnableSsl = false;
                    smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "pass");
                    smtpClient.Send(mail);

This code is working propely on localhost and I'm receiving an email.But when i deploy this code on server smtpClient.Send(mail); takes too much time and then throw timeout exception

Upvotes: 0

Views: 788

Answers (1)

dsdel
dsdel

Reputation: 1062

Therefor it is working locally I suspect that the server cannot communicate with the mail/smtp server due to firewall rules for example. I also do not see a problem in your code indicating some problems.

For diagnosis you can start a telnet client (eg. putty) and try to connect to the smtp server hostname using telnet mode and port 25.

You could also try diagnosing it with c# TcpClient itself:

        using (TcpClient tcpClient = new TcpClient())
        {
            Console.WriteLine("Connecting...");
            try
            {
                tcpClient.Connect(smptServer, 25);
            }
            catch (SocketException e)
            {
                Console.WriteLine("Connection error: {0}", e.Message);
                return;
            }


            if (!tcpClient.Connected)
            {
                Console.WriteLine("Unknown connection error...");
                return;
            }

            // get stream
            NetworkStream networkStream = null;
            Console.WriteLine("Get stream...");
            try
            {
                networkStream = tcpClient.GetStream();
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine("Stream error: {0}", e.Message);
                return;
            }
            finally
            {
                networkStream.Close();
                networkStream.Dispose();
                tcpClient.Close();
            }

            Console.WriteLine("Connection successfull...")

        }

If my assumption is correct the connection should not even be possible to establish.

Upvotes: 1

Related Questions