Configuring the PasswordRecovery To Send Email to an SSL-Enabled SMTP Client

Published 10 November 09 12:54 PM | Scott Mitchell

ASP.NET's PasswordRecovery provides a mechanism for users to recover their forgotten passwords. Depending on how user passwords are saved, the PasswordRecovery control will either email a user their password or it will reset the user's password to a new, auto-generated one and email them this new password. In either case, the PasswordRecovery control sends an email message. To accommodate this, your web application should have the SMTP settings defined in Web.config's section as described in this article: Sending Email in ASP.NET.

Certain SMTP servers (such as GMail's) only accept connections over SSL. Unfortunately, you cannot specify whether to send emails via SSL from the section; rather, you have to do it when you instantiate the SmtpClient object, via its EnableSsl property. This is problematic if you need to have the PasswordRecovery control send the user her password via an SMTP server that requires SSL. The workaround is to create an event handler for the PasswordRecovery control's SendingMail event, where you create your own SmtpClient object, set its EnableSsl property, and use it to send the MailMessage object the PasswordRecovery control is getting ready to send.

Protected Sub prResetPwd_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles prResetPwd.SendingMail
    Dim smtp As New SmtpClient
    smtp.EnableSsl = True

    Try
        smtp.Send(e.Message)
    Catch ex As Exception
        'Decide how to handle SMTP errors
    End Try

    'Instruct the control to cancel sending the email itself, since we just sent it
    e.Cancel = True
End Sub

Two things to note:

  1. The MailMessage object that the PasswordRecovery control is about to send is available via e.Message, and
  2. It is important to set e.Cancel to True. This tells the PasswordRecovery control to not send the email, which is what we want because we have already sent it with the SmtpClient object created in this event handler.

This concept can be extended to other ASP.NET Web controls that can automatically send emails (such as the CreateUserWizard control).

Happy Programming!

Filed under:

Comments

No Comments

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.