1

I am trying to send an email with c#. Everything seems to be ok no errors but when the programms tries to send the mail I get an exception : "System.Exception - Exception was not treated"

here is the code:

public void sendMail()
    {
        SmtpClient client = new SmtpClient();
        client.Port = 587;
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true;
        client.Timeout = 100;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");

        MailMessage mm = new MailMessage("[email protected]", "receiveremailaddress", "test", "test");
        mm.BodyEncoding = UTF8Encoding.UTF8;
        mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;


         client.Send(mm); // HERE I GET THE EXCEPTION !!!!!





    }
1
  • 1
    Bad practice. Any code above that throw will have no knowledge of what actually happened. If you don't mean to deal with the exception properly, then don't catch it. Commented May 30, 2014 at 13:53

1 Answer 1

2

The issue is your timeout is far too short try:

client.Timeout = 5000;

The default value is 100,000 (100 seconds), but smtp.gmail.com is fast enough that if you want to use 5000 it should be fine.

Also as per the above comment to your post; handle your exception (this is a very basic way of doing so).

try
{
...
}
catch(Exception ex)
{
Console.Writeline(ex);
}
Sign up to request clarification or add additional context in comments.

2 Comments

:) thank you! yes the timeout was to short ! I changed it to 5000 and now everything wokrs perfectly
@haddow64, your comment about handling the exception by printing it to the console is bad advice. You should always let the exception bubble up unless you intend to actually handle the error or log it in a top-level exception handler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.