Getting output from C# mail sending

1.6k Views Asked by At

I'm new to doing this sort of thing but I want to get the output from my application which sends mail. For example I want to be able to know if

  • A connection has been established
  • If the user was authenticated successfully
  • If the mail was sent succesffully etc.

I know how to send the mail using System.Net.Mail but is there any way to get this information ?

EDIT:

In the link David Stratton posted you can see the log and it receives the status codes like

  • 220 w2k Microsoft ESMTP MAIL Service, Version: 5.0.2195.6713 ready at Sat, 31 Dec 2005
  • 250-w2k Hello
  • 250-AUTH GSSAPI NTLM LOGIN..
  • 250-AUTH=LOGIN..
  • 250-TURN..
  • 250-ATRN..
  • 250-SIZE 2097152..
  • 250-ETRN..
  • 250-PIPELINING..
  • 250-DSN..
  • 250-ENHANCEDSTATUSCODES..
  • 250-8bitmime..
  • 250-BINARYMIME..
  • 250-CHUNKING..
  • 250-VRFY..
  • 250 OK..
  • MAIL FROM:..
  • 250 2.1.0 [email protected] OK..
  • RCPT TO:..
  • 550 5.7.1 Unable to relay for [email protected]

Is there a way to get these events live so that as each one comes I can display them?

3

There are 3 best solutions below

1
On

Put your SmtpClient.Send() call in a try/catch block and catch the below errors.

ArgumentNullException

  • message is Nothing.

InvalidOperationException

  • This SmtpClient has a SendAsync call in progress.
  • MailMessage.From is Nothing.
  • There are no recipients specified in MailMessage.To, MailMessage.CC, and MailMessage.Bcc properties.
  • DeliveryMethod property is set to Network and Host is Nothing.
  • DeliveryMethod property is set to Network and Host is equal to the empty string ("").
  • DeliveryMethod property is set to Network and Port is zero, a negative number, or greater than 65,535.

ObjectDisposedException

  • This object has been disposed.

SmtpException

  • The connection to the SMTP server failed.
  • Authentication failed.
  • The operation timed out.
  • EnableSsl is set to true but the DeliveryMethod property is set to SpecifiedPickupDirectory or PickupDirectoryFromIis.
  • EnableSsl is set to true, but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command.

SmtpFailedRecipientsException

  • The message could not be delivered to one or more of the recipients in MailMessage.To, MailMessage.CC, or MailMessage.Bcc.

Reference: http://msdn.microsoft.com/en-us/library/swas0fwc.aspx

2
On

If you want to create a log file based on the SMTP session, you can modify your .config file to do this automatically. Instructions here (archive.org backup). Same instructions can also be found at this SO answer.

1
On

I think that if at any point any of the 3 steps you mentioned would fail you would get an exception which you can catch with try/catch.

Critical point is probably the last one because once you queue the email in the SMTP server's queue you have no exceptions but it could still happen the email is not sent.