Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / ASP.NET / General / October 2007

Tip: Looking for answers? Try searching our database.

SMTP Email Not Working from Application_Error handler in ASP.NET 2

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
PK9 - 02 Oct 2007 16:33 GMT
I have an ASP.NET 2.0 Web Application.  I am trying to send an email to
myself from Global.asax in the Application_Error event handler.  I have been
able to successfully send emails from the rest of the application using the
exact same logic.  For some reason, it does not work in global.asax.  I get a
"Failure Sending Mail" error message with a more detailed explanation of
"Unable to read data from the transport connection: An existing connection
was forcibly closed by the remote host.".  This is in a hosted environment,
and it IS working for other pages in the app (making me think I need to do
something different in the Application_Error function.

I am using the System.Net.Mail class.  Below is my code and the detailed
error (notice I have some general information stored in web.config which is
pasted below as well):

GLOBAL.ASAX
--------------------------------------------------------
void Application_Error(object sender, EventArgs e)
   {
       // Code that runs when an unhandled error occurs
       Exception ex = Server.GetLastError();
    string strEmailAddressTo = "myemail@test.com";
       string strEmailAddressFrom = "myemail@test.com";
           

       string ErrorMessage = ex.Message +
           "\nSOURCE: " + ex.Source +
           "\nFORM: " + Request.Form.ToString() +
               "\nQUERYSTRING: " +
               Request.QueryString.ToString() +
               "\nTARGETSITE: " + ex.TargetSite +
              "\nSTACKTRACE: " + ex.StackTrace;

        //1) Create the mail message instance
       MailMessage mm = new MailMessage(strEmailAddressFrom,
strEmailAddressTo);

       //2) Assign the Mail Message's Properties
       // Subject        
       mm.Subject = "ERROR OCCURRED";

       //3) Body
       mm.Body = ErrorMessage.ToString();
       mm.IsBodyHtml = false;

       //4) Create the SMTP Client Object
       SmtpClient smtp = new SmtpClient();

       
       //5) Send the mail message (will use the web.config settings)
       smtp.Send(mm);
}

web.config
------------------------------------------------------------
<system.net>
   <mailSettings>
     <smtp>
       <network host="[mynetworkHost]" port="25" />
     </smtp>
   </mailSettings>
 </system.net>

DETAILED ERROR MESSAGE:
-------------------------------------------------------------
<ExceptionInformation><AdditionalInformationProperty
ExceptionManager.MachineName="XXXXX" ExceptionManager.TimeStamp="10/2/2007
1:32:25 AM"
ExceptionManager.FullName="Microsoft.ApplicationBlocks.ExceptionManagement,
Version=1.0.2830.35366, Culture=neutral, PublicKeyToken=null"
ExceptionManager.AppDomainName="/LM/w3svc/814863/root-11-128357766911129800"
ExceptionManager.ThreadIdentity="" ExceptionManager.WindowsIdentity="NT
AUTHORITY\NETWORK SERVICE" /><Exception
ExceptionType="System.Net.Mail.SmtpException" StatusCode="GeneralFailure"
Message="Failure sending mail."
Data="System.Collections.ListDictionaryInternal" TargetSite="Void
Send(System.Net.Mail.MailMessage)" Source="System"><StackTrace>   at
System.Net.Mail.SmtpClient.Send(MailMessage message)
  in  \\[webpath]\web\Global.asax:line 101</StackTrace><Exception
ExceptionType="System.IO.IOException" Message="Unable to read data from the
transport connection: An existing connection was forcibly closed by the
remote host." Data="System.Collections.ListDictionaryInternal"
TargetSite="Int32 Read(Byte[], Int32, Int32)" Source="System"><StackTrace>  
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32
size)
  at System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32
count)
  at System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32
count)
  at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader
caller, Boolean oneLine)
  at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
  at System.Net.Mail.SmtpReplyReader.ReadLine()
  at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
  at System.Net.Mail.DataStopCommand.Send(SmtpConnection conn)
  at System.Net.Mail.SmtpConnection.OnClose(Object sender, EventArgs args)
  at System.Net.ClosableStream.Close()
  at System.Net.Mail.MailWriter.Close()
  at System.Net.Mail.SmtpClient.Send(MailMessage
message)</StackTrace><Exception
ExceptionType="System.Net.Sockets.SocketException" ErrorCode="10054"
SocketErrorCode="ConnectionReset" NativeErrorCode="10054" Message="An
existing connection was forcibly closed by the remote host"
Data="System.Collections.ListDictionaryInternal" TargetSite="Int32
Receive(Byte[], Int32, Int32, System.Net.Sockets.SocketFlags)"
Source="System"><StackTrace>   at System.Net.Sockets.Socket.Receive(Byte[]
buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
  at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset,
Int32
size)</StackTrace></Exception></Exception></Exception></ExceptionInformation>

Signature

PK9

Aidy - 02 Oct 2007 17:18 GMT
The actual problem is probably the code that is throwing the exception not
tidying up its network connects, mail client etc, so that when the error
event in your global.asax fires your network connections are not in a
suitable condition to send e-mail.  This will be doubly so if it is
e-mailing that is throwing your original exception.

>I have an ASP.NET 2.0 Web Application.  I am trying to send an email to
> myself from Global.asax in the Application_Error event handler.  I have
[quoted text clipped - 112 lines]
> Int32
> size)</StackTrace></Exception></Exception></Exception></ExceptionInformation>
PK9 - 02 Oct 2007 21:47 GMT
Thank you for your response.  So how would one handle this?  I assume that
catching errors in the global.asax and emailing a sys admin is typical
practice.  You may be correct that the network connects are not in a suitable
condition to send email -- but I'm not sure how to remedy that.

Just for further information, this happens regardless of the type of error
thrown (i.e. dividebyzeroexception, custom applicationexception, etc).  THe
email functionality will simply not work from the Application_Error event
handler.

Any ideas on how to remedy this?
Signature

PK9

> The actual problem is probably the code that is throwing the exception not
> tidying up its network connects, mail client etc, so that when the error
[quoted text clipped - 118 lines]
> > Int32
> > size)</StackTrace></Exception></Exception></Exception></ExceptionInformation>
Aidy - 03 Oct 2007 09:57 GMT
I'd probably start with some basic debugging issues like attempting to send
e-mail from other events in the global.asax like application start or
session start etc to see if it is sending mail from a certain event (the
error one) or all events.

> Thank you for your response.  So how would one handle this?  I assume that
> catching errors in the global.asax and emailing a sys admin is typical
[quoted text clipped - 144 lines]
>> > Int32
>> > size)</StackTrace></Exception></Exception></Exception></ExceptionInformation>
Alexey Smirnov - 02 Oct 2007 17:24 GMT
> I have an ASP.NET 2.0 Web Application.  I am trying to send an email to
> myself from Global.asax in the Application_Error event handler.  I have been
[quoted text clipped - 107 lines]
> --
> PK9

1. How do you get that error message?
2. Did you tried to specify default credential in mailSettings?
PK9 - 02 Oct 2007 21:53 GMT
I get this problem any time an error is thrown within the application and the
Application_Error event handler is called.  I have a site in production, and
to test the error handling in production, I have created a button with an
event handler that when clicked will throw an exception.  I have tested it by
adding "throw new ApplicationException("This is a test exception being
thrown...");" and by throwing a named exception "throw new
DivideByZeroException();".

Both correctly go to the Application_Error event handler, but the email
portion fails everytime.

I'm at a loss.

Not sure which "default credentials" you're referring to.  I have the
following settings specified in web.config, but I've tried to add additional
information such as username and password to the web.config as well (with no
luck):
web.config
------------------------------------------------------------
<system.net>
    <mailSettings>
      <smtp>
        <network host="[mynetworkHost]" port="25" />
      </smtp>
    </mailSettings>
</system.net>

Signature

PK9

> > I have an ASP.NET 2.0 Web Application.  I am trying to send an email to
> > myself from Global.asax in the Application_Error event handler.  I have been
[quoted text clipped - 110 lines]
> 1. How do you get that error message?
> 2. Did you tried to specify default credential in mailSettings?
Alexey Smirnov - 02 Oct 2007 22:35 GMT
> I get this problem any time an error is thrown within the application and the
> Application_Error event handler is called.  I have a site in production, and
[quoted text clipped - 22 lines]
>      </mailSettings>
> </system.net>

Well, the code looks correct but I'm not sure what exactly that error
message means. I would try to simplify Application_Error to send just
a test email to see if it helps and I check if other part of code
where email is working has the same identity as NT AUTHORITY\NETWORK
SERVICE (it stays in exception)

Response.Write(Environment.UserName);

Maybe you use an impersonation there?

BTW, check ASP.NET Health Monitoring, it can do the same using
standard web.config configuration.
http://msdn2.microsoft.com/en-us/library/ms178701.aspx

Example:

<healthMonitoring enabled="true">
     <providers>
       <add name="EmailProvider"
          type="System.Web.Management.SimpleMailWebEventProvider"
          to="@"
          subjectPrefix="Error: "
          buffer="true"
          bufferMode="Notification" />
     </providers>
     <rules>
       <add provider="EmailProvider" name="All App Events"
eventName="All Errors" />
     </rules>
   </healthMonitoring>
PK9 - 03 Oct 2007 00:49 GMT
Alexey - thanks for responding.  Unfortunately I've checked the credentials
and the same username is being used in both situations (the working version
and the error version).   I think "Aidy" may have been on to something when
he suggested that when an error fires, the network connections are not in a
suitable condition to send email -- I'm just not sure how to remedy that.

It doesn't look like anyone else has any answers so far unfortunately.

Signature

PK9

> > I get this problem any time an error is thrown within the application and the
> > Application_Error event handler is called.  I have a site in production, and
[quoted text clipped - 53 lines]
>       </rules>
>     </healthMonitoring>

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.