system.net.mail: Having problems sending webpage as the body of my email.

Hi All -  I'm trying to send a webpage as the body of my email message and I'm getting the following error:


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 xx.xx.xx.xxx:80

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 xx.xx.xx.xxx:80

Source Error:


Line 17:
Line 18:     Protected Sub btnEmailTest_Click(sender As Object, e As EventArgs) Handles btnEmailTest.Click
Line 19:         emailLogic.EmailConfirmation()
Line 20:         lbEmailStatus.Text = "Email Sent!"
Line 21:     End Sub


Here's the 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 xx.xx.xx.xxx:80]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +273
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +584

[WebException: Unable to connect to the remote server]
   System.Net.HttpWebRequest.GetResponse() +8765848
   Email.DownloadFromURL(String URLToRead) +149
   Email.EmailConfirmation() +31
   mainMenu.btnEmailTest_Click(Object sender, EventArgs e) in D:\Websites\DesignRequest\mainMenu.aspx.vb:19
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +155
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804

Open in new window


Here's my code:

Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Net
Imports System.Net.Mail

Public Class Email

    Public Sub EmailConfirmation()
        Dim mailText As String = DownloadFromURL("http://www.mywebsite.com/basicEmail.html")

        Dim mail As New MailMessage()
        mail.From = New MailAddress("confirmation@mywebsite.com", "Confirmation")
        mail.To.Add("john.smith@mywebsite.com")
        mail.Subject = "Email Confirmation"
        mail.Body = mailText
        mail.IsBodyHtml = True

        Dim smtp As New SmtpClient

        smtp.Send(mail)
    End Sub

    Private Function DownloadFromURL(ByVal URLToRead As String) As String
            Dim WebRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(URLToRead), HttpWebRequest)
            WebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials
            WebRequest.Accept = "*/*"
            WebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)"
            WebRequest.AllowAutoRedirect = True

            Dim WebResponse As HttpWebResponse = DirectCast(WebRequest.GetResponse(), HttpWebResponse)
            Dim s As Stream = WebResponse.GetResponseStream()
            Dim sr As New StreamReader(s)

            Return sr.ReadToEnd()
    End Function

End Class

Open in new window


If I run the code locally (on my laptop) IT WORKS and I do not get this error.  The code runs perfectly and the email is sent.  

When I execute this code on the server (Windows Server 2012 running IIS8)  I get this error message.

HELP!!!
cdemott33Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Daniel Van Der WerkenIndependent ConsultantCommented:
Your local system has an unhindered connection to the mail server. Your IIS server doesn't.

Log into the IIS server and run some tests to check your connectivity to the SMTP server. For example:

How to Check SMTP Connection Manually

You may need to engage the networking folks of your business to get this functional.
0
cdemott33Author Commented:
Thanks for the suggestions but I've got a wrench to through at this situation.

If I change the mail.body to TEXT (rather than using the DownloadFromURL function) and move it to my server, the server delivers the email without issue.

        mail.Body = "This is the body of my email."
        mail.IsBodyHtml = False

Open in new window


SO.... Now I believe the problem MUST have something to do with this block of code...

Private Function DownloadFromURL(ByVal URLToRead As String) As String
            Dim WebRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(URLToRead), HttpWebRequest)
            WebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials
            WebRequest.Accept = "*/*"
            WebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)"
            WebRequest.AllowAutoRedirect = True

            Dim WebResponse As HttpWebResponse = DirectCast(WebRequest.GetResponse(), HttpWebResponse)
            Dim s As Stream = WebResponse.GetResponseStream()
            Dim sr As New StreamReader(s)

            Return sr.ReadToEnd()
    End Function

Open in new window


I'm performing some test now.  This code works perfect on two other servers so it must have something to do with this particular server.  Just a theory at this point.  Stand by.
0
cdemott33Author Commented:
Okay... now I discovered a completely NEW problem.  (Related to the original problem I believe.)

When I open a browser on my server and go to my website the page doesn't load.  I can load any other page I want on the world wide web, but the website that is hosted on the box will not load????

Any idea?
0
Daniel Van Der WerkenIndependent ConsultantCommented:
I think all the evidence points to that this particular server has obstructed Internet access. Sounds like a routing or firewall issue. Can you engage your network engineers/admins to assist in determining if there is a problem with connections to the Internet?

I have to deal with this kind of stuff almost every month with my own network personnel at the company I work with. It's not a software code issue, but it is a network issue.
0
CtrlAltDlCommented:
Did you confirm that the variable "URLToRead" is in fact the web site you were expecting?

If so then it sounds like it might be a DNS issue.  Is the URLToRead local (on same LAN) or remote (via Internet)?

If it is local then the server name needs to resolve to the local IP address (unless your router supports Hairpin NAT).  If it is remote than I would check what DNS servers your server uses.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.