Search code examples
asp.netasp.net-membershipasp.net-2.0createuserwizard

CreateUserWizard - Preventing user creation if confirmation email cannot be sent


I am trying to fix the behavior of a CreateUserWizard control in ASP.NET 2.0. With a fairly naive, out-of-the-box implementation, if you enter an email address that does not exist, or there is some other error sending the email, you get a YSOD showing the ugly details of the SMTP error, plus the user account is created anyway. Handling the SendMailError does not seem to help, as it is fired after the user is already created.

Ideally, an email error would cause an "invalid email address" error message (or something to that effect) to be displayed. Seems like this should be pretty easy, but after quite a bit of looking around I haven't found an answer. Anybody have any solutions?


Solution

  • This is what I do. It's not perfect, but it helps.

    protected void CreateUserWizard1_SendMailError(object sender, SendMailErrorEventArgs e)
    {
        // e.Exception can be one of the exceptions generated from SmtpClient.Send(MailMessage)
        if (e.Exception is SmtpFailedRecipientException)
        {
            // The message could not be delivered to one or more of the recipients in To, CC, or BCC()()().
            // TODO: Set an error message on the page
            e.Handled = true;
    
            // Since the user has already been created at this point, we need to remove them.
            Membership.DeleteUser(CreateUserWizard1.UserName);
    
            // Set an internal flag for use in the ActiveStepChanged event.
            emailFailed = true;
    
            return;
        }
    }
    
    protected void CreateUserWizard1_ActiveStepChanged(object sender, EventArgs e)
    {
        if (CreateUserWizard1.ActiveStep != CreateUserWizard1.CompleteStep)
            return;
    
        if (emailFailed)
        {
            // If the email failed, keep the user on the first step.
            CreateUserWizard1.ActiveStepIndex = 0;
            return;
        }
    }