How to customize the e-mail sent by PasswordRecovery In The SendingMail Event and Include The Newly Reset Password In The E-mail

Last post 09-10-2009 11:33 AM by wschwerdt. 5 replies.

Sort Posts:

  • How to customize the e-mail sent by PasswordRecovery In The SendingMail Event and Include The Newly Reset Password In The E-mail

    05-16-2009, 10:53 PM
    • Member
      point Member
    • jon333
    • Member since 01-04-2007, 7:41 PM
    • Posts 40

    Hi,
    I have a multi-lingual application that needs to send different password recovery e-mail messages to the user based on their language preference.  The problem is that I cannot simply read one .txt file from the MailDefinition of the PasswordRecovery control due to this and when I try to programatically customize the e-mail sent by the system the <% Username %> and <% Password %> tokens are not being replaced.

    How can I customize the e-mail message sent to the user when they are resetting their password and include the new password in the e-mail?

    Please note that I get an error when I manually try to reset the password in the SendingMail event, but I could not find another way to obtain a reset password for the e-mail.

    Protected Sub PasswordRecovery1_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles PasswordRecovery1.SendingMail
            Dim strFinalBody As String = TryCast(GetGlobalResourceObject("Emails", "PasswordResetBody"), String)
    
            Try
                Dim usr As MembershipUser = Membership.GetUser(PasswordRecovery1.UserName)
                'Returns object not set to an instance of an object error
                'Passwords are hashed and only resets are enabled.
                Dim password As String = usr.ResetPassword(PasswordRecovery1.Answer)
    
                MsgBox(password.ToString)
    
                e.Message.From = New MailAddress("test@test.com")
                e.Message.CC.Add(New MailAddress("devemail@test.com"))
                e.Message.Subject = TryCast(GetGlobalResourceObject("Emails", "PasswordResetSubject"), String)
                'Perform subsitution
    
                strFinalBody = strFinalBody.Replace("&lt;% UserName %&gt;", PasswordRecovery1.UserName)
                strFinalBody = strFinalBody.Replace("<% Password %>", password)
    
                strFinalBody = strFinalBody.Replace("<%UserName%>", PasswordRecovery1.UserName)
                strFinalBody = strFinalBody.Replace("<%Password%>", password)
    
                strFinalBody = strFinalBody.Replace("&lt;% UserName %&gt;", PasswordRecovery1.UserName)
                strFinalBody = strFinalBody.Replace("&lt;% Password %&gt;", password)
    
                strFinalBody = strFinalBody.Replace("&lt;%UserName%&gt;", PasswordRecovery1.UserName)
                strFinalBody = strFinalBody.Replace("&lt;%Password%&gt;", password)
    
                e.Message.Body = strFinalBody
                e.Message.IsBodyHtml = True
            Catch ex As Exception
                MsgBox(ex.Message.ToString)
                Response.Redirect("~/Errors/Error.aspx")
            End Try
        End Sub
     
  • Re: How to customize the e-mail sent by PasswordRecovery In The SendingMail Event and Include The Newly Reset Password In The E-mail

    05-17-2009, 2:43 AM
    • Participant
      1,082 point Participant
    • Dave_Winchester
    • Member since 03-03-2006, 3:13 PM
    • United Kingdom
    • Posts 340

    Hi jon333

    You may already know this, but you can set the body template of password recovery email by using the mail definition of the PasswordRecovery e.g.

    <MailDefinition
      From="noreply@email.com"
      Subject="Your password has been reset"
      IsBodyHtml="true"
      BodyFileName="~/Templates/PasswordRecoveryMail.htm" />
     =====================
    PasswordRecoveryMail.htm 
     ===================== 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <title></title>
    </head>
    <body>
    <p><%UserName%></p>
    <p><%Password%></p>
    </body>
    </html
    This way you could, as opposed to using concatentaion to build the body of the email have different templates etc... and change this using programmatically.
    If this does not help, check out this. 
     
     
      
    David Winchester

    Please mark as answer if this is the solution.
  • Re: How to customize the e-mail sent by PasswordRecovery In The SendingMail Event and Include The Newly Reset Password In The E-mail

    05-17-2009, 12:14 PM
    • Member
      point Member
    • jon333
    • Member since 01-04-2007, 7:41 PM
    • Posts 40

    Sorry Dave, I can't use the mail definition property of the PasswordRecovery control in my case.  The problem is that I must send e-mails in different languages (e.g. different templates for each language).  The rest of the site uses a database driven localization/resource model where all the internationalized text or resources are stored in the DB instead of .resx files.

     So the code I have above already works to send the correct e-mail for the user's language preference.  The problem is that the UserName and Password placeholders are not getting replaced when the e-mail gets sent out even though they are in the body of the e-mail (e.g. the user sees <% Username %> in the body of the e-mail) .  I use the same method when creating a new user account and it sends a confirmation e-mail and it works fine.  Another problem is how to find what to replace the password with since the application only allows hashed passwords to be reset not retrieved.

  • Re: How to customize the e-mail sent by PasswordRecovery In The SendingMail Event and Include The Newly Reset Password In The E-mail

    05-17-2009, 2:40 PM
    • Participant
      1,082 point Participant
    • Dave_Winchester
    • Member since 03-03-2006, 3:13 PM
    • United Kingdom
    • Posts 340

    Hi jon

    OK, I understand now.

    I will try test this out on a test website I use for answering posts. Am about to eat dinner though, so without risking my life from the mrs. I will get back to you ASAP.

    Dave

    David Winchester

    Please mark as answer if this is the solution.
  • Re: How to customize the e-mail sent by PasswordRecovery In The SendingMail Event and Include The Newly Reset Password In The E-mail

    06-03-2009, 5:03 AM
    • Member
      199 point Member
    • chayadi
    • Member since 05-28-2009, 4:23 AM
    • Posts 66
    CMIIW: Haven't test this, but i think you can change the BodyFileName property on the page load base on the user language preference, right?
    Please "Mark as Answer" and "Mark as Resolved" if the post solved your problem.
    This will help other with the same problem in future.
  • Re: How to customize the e-mail sent by PasswordRecovery In The SendingMail Event and Include The Newly Reset Password In The E-mail

    09-10-2009, 11:33 AM
    • Member
      6 point Member
    • wschwerdt
    • Member since 07-10-2009, 8:12 AM
    • Geneva Switzerland
    • Posts 3

    I had the same problem - a database-based multilanguage application.

    Setting the mail body content in the sending_mail event is too late to switch to another mail body file and at that stage it is also imppossible to acces the <%UserName%> and <%Password%> placeholders (see http://blog.dotnet-oldenburg.de/2009/03/23/aspnet-passwordrecovery-control-neues-passwort-programmatisch-auslesen/ for those reading German).

    What does work, however, is to

    (1) place the password recovery control in a user control (.ascx file).

    (2) place the user control in an .aspx file which has an event specified that reacts to a change in language (see http://www.odetocode.com/articles/450.aspx on how to do that).


    This has the effect that every time there is a change in language (say, in an associated master page) the .aspx page (and, hence, the .ascx user control) reloads.

    Now, all you need to do is to set up a streamer object updating the .txt file for the password-recovery email in the Page_Load event of the user control (see http://aspnet.4guysfromrolla.com/articles/072303-1.2.aspx how to handle streamer objects).

    For convenience, I just copy/paste my code from the .ascx file's Page_Load event that works fine for me . I store / update the language information in the Session["WorkingLanguageCode"] dictionary object. Note also that I use the MySQL database system and the related MySQLClient, so you will have to adapt your data extraction logic according to your settings. I just leave it here for illustration purposes...

    ...

    using System.IO; // needed for the text streamer object.

    ...

    protected void Page_Load(object sender, EventArgs e)

    {

    ...

     

    // Get language-specific email text data from cd_page_contents (database table containing all my language-specific data)...

    MySQLDatabaseConnection DBConnection = new MySQLDatabaseConnection("CodeListDBConnString");

    try

    {

    DBConnection.connectDB();

     

    //Get Label Data for this page and Working Language Code

    string SQL = "SELECT object_type, " + Session["WorkingLanguageCode"] + " FROM `cd_page_contents` WHERE page_name = 'email.passwordrecovery'";

    ...

    MySql.Data.MySqlClient.MySqlDataReader myReader = DBConnection.SelectData(SQL);

    string isObjectType;

    string isPropertyValue;

     

    if (myReader != null)

    {

       while (myReader.Read())

       {

        isObjectType = myReader["object_type"].ToString();

        isPropertyValue = myReader[Session["WorkingLanguageCode"].ToString()].ToString();

        switch (isObjectType)

        {

        case "EmailHeading": isEmailHeading = isPropertyValue; break;

        case "EmailText1": isEmailText1 = isPropertyValue; break;

        case "EmailText2": isEmailText2 = isPropertyValue; break;

        case "EmailText3": isEmailText3 = isPropertyValue; break;

        case "EmailText4": isEmailText4 = isPropertyValue; break;

        case "EmailTextLogin": isEmailTextLogin = isPropertyValue; break;

        case "EmailTextPassword": isEmailTextPassword = isPropertyValue; break;

        case "EmailSignature1": isEmailSignature1 = isPropertyValue; break;

        case "EmailSignature2": isEmailSignature2 = isPropertyValue; break;

        default: break;

        } // end switch

    } // end while

    } // end myReader != null

    } // end try

    catch (MySql.Data.MySqlClient.MySqlException ex)

    {

    ...

    }

    finally

    {

    DBConnection.disconnectDB();

    }

     

    // rewrite the password recovery email...

    string ifFileName = Server.MapPath("~/login/passwordrecoverymail.txt");

     

    //Get a StreamReader class that can be used to read the file

    StreamWriter ioStreamWriter = File.CreateText(ifFileName);

    ioStreamWriter.WriteLine("<p style=\"font-family: Verdana Ref, Verdana, Arial, Calibri,Helvetica, Sans-Serif; font-size:9pt\">");

    ioStreamWriter.WriteLine("<br/>" + isEmailText1);

    ioStreamWriter.WriteLine("<br/><br/><br/>" + isEmailText2);

    ioStreamWriter.WriteLine("<br/><br/>" + isEmailTextLogin + " <%UserName%>");

    ioStreamWriter.WriteLine("<br/><br/>" + isEmailTextPassword + " <%Password%>");

    ioStreamWriter.WriteLine("<br/><br/><br/><b>" + isEmailText3 + " </b> " + isEmailText4);

     

    // close streamer...

    ioStreamWriter.Close();

     

    // set response email properties

    PasswordRecovery_Control.MailDefinition.IsBodyHtml = true;

    PasswordRecovery_Control.MailDefinition.BodyFileName = "~/login/passwordrecoverymail.txt";

    }

     

    ...

     

    That should work.

    Don't forget to set the .From property of the email definition as well as your smtp settings in the web.config file.

     

    Well, I hope this is of help to others having a similar headache... just as much as the other contributions on this forum are of help to me.

     

    Have fun!

     

    Wolfgang

    (in case of questions, contact me at wolfgang.schwerdt@freenet.de)

     

     

     

Page 1 of 1 (6 items)