Solved

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

Posted on 2014-11-13
5
175 Views
Last Modified: 2015-01-22
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!!!
0
Comment
Question by:cdemott33
  • 2
  • 2
5 Comments
 
LVL 19

Expert Comment

by:Daniel Van Der Werken
ID: 40440654
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
 

Author Comment

by:cdemott33
ID: 40440917
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
 

Author Comment

by:cdemott33
ID: 40441134
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
 
LVL 19

Expert Comment

by:Daniel Van Der Werken
ID: 40442771
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
 
LVL 14

Accepted Solution

by:
CtrlAltDl earned 500 total points
ID: 40443303
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

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now