SmtpClient Hanging

Has anyone gotten SmtpClient to work with gmail? I'm trying to narrow down where the problem is, and when I call client.Send(msg), my app hangs. Here's the relevant code:

MailMessage mm = new MailMessage();
mm.Body = formattedorder;  // A string that contains HTML code
mm.IsBodyHtml = true;
mm.BodyEncoding = Encoding.UTF8;
mm.Subject = "Super Secret Test Mail";
mm.To.Add("[email protected]");
mm.From = new MailAddress("[email protected]");

SmtpClient client = new SmtpClient("smtp.gmail.com", 465) {
            Credentials = new NetworkCredential("[email protected]", "passwd"),
            Timeout = 1000,
            EnableSsl = true
};
try {
    client.Send(mm);  // Hangs here
}
catch (Exception ex) {
    var builder2 = new AlertDialog.Builder(this);
    builder2.SetTitle("Error!");
    builder2.SetMessage(ex.Message + "\n" + ex.InnerException);
    builder2.SetCancelable(false);
    builder2.SetPositiveButton("OK", delegate { });
    builder2.Show();
}


Names and passwords have been changed to protect the guilty.

I set the timeout to what I think is a very small value. According to Microsoft documentation, I believe that is one second.

This exact code works just fine when I use my Frontier email account to send email. I have three email accounts to use to test with, and it's the only one of the three I can get to work. The difference may be that the Frontier server doesn't use SSL.

Even if I can't figure out why using the gmail server fails, I really need to know why it doesn't timeout. As it is now, my app just hangs. It needs to hit that catch clause and fail gracefully. Does anyone have any idea why it won't timeout? Has anyone gotten SmtpClient to work with gmail?

Thanks so much!

-Karen

Posts

  • I was working on this today actually, if you change the port to 587 and add the following code, it worked for me.

    System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((_1, _2, _3, _4) => true);

  • KarenCateKarenCate USMember ✭✭

    You, sir, rock!

    Just to make sure... this looks like something that needs to be set once, not for each email that is sent. Do you have an "if null" check before that statement? Or do you create a new handler for each email message?

    On a related note, all of the examples I've found create a new SmtpClient for each email sent. Is that appropriate? Or should I create one and reuse it if it exists?

    Thanks again!

  • I just put that code into the static constructor for the email sending class so it is only called once, but you can do it however you want.

    I have yet to do a whole lot with the SmtpClient class as yet, but it seems like you can create one class and send multiple MailMessage using it.

Sign In or Register to comment.