Solved

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

Posted on 2014-11-13
5
186 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 20

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 20

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Runtime Error 2 28
Export import database 4 42
Change Format on Data when exporting to Excel 4 23
Message not shown 5 30
If you don't have the right permissions set for your WordPress location in IIS, you won't be able to perform automatic updates. Here's how to fix the problem.
If you are a web developer, you would be aware of the <iframe> tag in HTML. The <iframe> stands for inline frame and is used to embed another document within the current HTML document. The embedded document could be even another website.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Edureka is one of the fastest growing and most effective online learning sites.  We are here to help you succeed.

911 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