Friday, November 6, 2009

ASP.NET PasswordRecovery Control and GMail

I recently had need to whip up a quick ASP.NET web site with authentication. Nothing fancy, so the default ASP.NET Membership provider tables and account controls worked fine. The one problem I ran into was that I needed to route the email the MembershipProvider and PasswordRecovery control create through GMail. You see, GMail uses secure connections and the control doesn't seem to offer built in support. But it isn't too hard to get it working.

Here's the approach I ended up with.

protected override void OnInit(EventArgs e)

PasswordRecoveryControl.SendingMail += PasswordRecoveryControl_SendingMail;

void PasswordRecoveryControl_SendingMail(object sender, MailMessageEventArgs e)
// Create network credentials from SMTP configuration settings.
var config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
var settings = (MailSettingsSectionGroup)config.GetSectionGroup("");
var credentials = new NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password);

// Send message over secure connection.
var mailClient = new SmtpClient(settings.Smtp.Network.Host, settings.Smtp.Network.Port);
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = credentials;

// Prevent control from sending message via default implementation.
e.Cancel = true;

Canceling the event still results in success as far as the control is concerned. This means the SuccessText and SuccessUrl properties on the control behave the way you want them to if not quite the way you might expect them to.