/// <summary> /// Sends notification email to the administrator. /// </summary> private void SendAdminNotification(UserInfo ui) { if (NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { var resolver = MembershipResolvers.GetRegistrationResolver(ui); var emailTemplate = EmailTemplateProvider.GetEmailTemplate(AdminApprovalRequired ? "Registration.Approve" : "Registration.New", CurrentSiteName); if (emailTemplate == null) { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = FromAddress; message.Recipients = ToAddress; message.Subject = GetString("RegistrationForm.EmailSubject"); try { EmailSender.SendEmailWithTemplateText(CurrentSiteName, message, emailTemplate, resolver, false); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } }
/// <summary> /// Sends new registration notification e-mail to administrator. /// </summary> private void SendRegistrationNotification(UserInfo ui) { var currentSiteName = SiteContext.CurrentSiteName; // Notify administrator if ((ui != null) && !String.IsNullOrEmpty(currentSiteName) && (ShoppingCartControl.SendNewRegistrationNotificationToAddress != "")) { EmailTemplateInfo mEmailTemplate = null; MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui); if (SettingsKeyInfoProvider.GetBoolValue(currentSiteName + ".CMSRegistrationAdministratorApproval")) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName); } if (mEmailTemplate == null) { // Email template not exist EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { // Initialize email message EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, ECommerceSettings.SendEmailsFrom(currentSiteName)); message.Subject = GetString("RegistrationForm.EmailSubject"); message.Recipients = ShoppingCartControl.SendNewRegistrationNotificationToAddress; message.Body = mEmailTemplate.TemplateText; try { // Add template metafiles to e-mail EmailHelper.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); // Send e-mail EmailSender.SendEmailWithTemplateText(currentSiteName, message, mEmailTemplate, resolver, false); } catch { // Email sending failed EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } }
/// <summary> /// Send e-mail to administrator about new registration. /// </summary> /// <param name="administrationApproval">Indicates if administration approval is required</param> private void SendEmailToAdministrator(bool administrationApproval) { MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(RegisteredUser); string currentSiteName = SiteContext.CurrentSiteName; var template = EmailTemplateInfo.Provider.Get(administrationApproval ? "Registration.Approve" : "Registration.New", SiteContext.CurrentSiteID); if (template == null) { var logData = new EventLogData(EventTypeEnum.Error, "RegistrationForm", "GetEmailTemplate") { EventUrl = RequestContext.RawURL, UserName = CurrentUser.UserName, SiteID = SiteContext.CurrentSiteID }; Service.Resolve <IEventLogService>().LogEvent(logData); } else { // E-mail template ok string from = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyInfoProvider.GetValue(currentSiteName + ".CMSNoreplyEmailAddress")); if (!String.IsNullOrEmpty(from)) { // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = AdministratorEmail; email.From = from; email.Subject = GetString("RegistrationForm.EmailSubject"); try { EmailSender.SendEmailWithTemplateText(currentSiteName, email, template, resolver, true); } catch { Service.Resolve <IEventLogService>().LogError("Membership", "RegistrationApprovalEmail"); } } else { Service.Resolve <IEventLogService>().LogError("RegistrationApproval", "EmailSenderNotSpecified"); } } }
/// <summary> /// Sends notification email to the administrator. /// </summary> private void SendAdminNotification(UserInfo ui) { if (NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { var resolver = MembershipResolvers.GetRegistrationResolver(ui); var emailTemplate = EmailTemplateProvider.GetEmailTemplate(AdminApprovalRequired ? "Registration.Approve" : "Registration.New", CurrentSiteName); if (emailTemplate == null) { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(emailTemplate, FromAddress); message.Recipients = ToAddress; // Enable macro encoding for body resolver.Settings.EncodeResolvedValues = true; message.Body = resolver.ResolveMacros(emailTemplate.TemplateText); // Disable macro encoding for plaintext body and subject resolver.Settings.EncodeResolvedValues = false; message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(emailTemplate, GetString("RegistrationForm.EmailSubject"))); message.PlainTextBody = resolver.ResolveMacros(emailTemplate.TemplatePlainText); message.CcRecipients = emailTemplate.TemplateCc; message.BccRecipients = emailTemplate.TemplateBcc; try { // Attach template meta-files to e-mail EmailHelper.ResolveMetaFileImages(message, emailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); EmailSender.SendEmail(CurrentSiteName, message); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } }
/// <summary> /// OK click handler (Proceed registration). /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { String siteName = SiteContext.CurrentSiteName; #region "Banned IPs" // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration)) { ShowError(GetString("banip.ipisbannedregistration")); return; } #endregion #region "Check Email & password" string[] siteList = { siteName }; // If AssignToSites field set if (!String.IsNullOrEmpty(AssignToSites)) { siteList = AssignToSites.Split(';'); } // Check whether another user with this user name (which is effectively email) does not exist UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail.Text); SiteInfo si = SiteContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si)); if ((ui != null) || (siteui != null)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text))); return; } // Check whether password is same if (passStrength.Text != txtConfirmPassword.Text) { ShowError(GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch")); return; } if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength)); return; } if (!passStrength.IsValid()) { ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName)); return; } if ((!txtEmail.IsValid()) || (txtEmail.Text.Length > EMAIL_MAX_LENGTH)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"), EMAIL_MAX_LENGTH)); return; } #endregion #region "Captcha" // Check if captcha is required and verify captcha text if (DisplayCaptcha && !scCaptcha.IsValid()) { // Display error message if catcha text is not valid ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError")); return; } #endregion #region "User properties" var userEmail = txtEmail.Text.Trim(); ui = new UserInfo(); ui.PreferredCultureCode = ""; ui.Email = userEmail; ui.FirstName = txtFirstName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName); ui.MiddleName = ""; ui.UserMFRequired = chkUseMultiFactorAutentization.Checked; // User name as put by user (no site prefix included) var plainUserName = userEmail; ui.UserName = plainUserName; // Check if the given email can be used as user name if (!ValidationHelper.IsUserName(plainUserName)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.UserNameNotValid"), HTMLHelper.HTMLEncode(plainUserName))); return; } // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(siteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(plainUserName, si); } ui.Enabled = EnableUserAfterRegistration; ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer); ui.UserCampaign = Service <ICampaignService> .Entry().CampaignCode; ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None; ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = false; if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is required requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"); if (requiresAdminApprove) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath); } #endregion #region "Reserved names" // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true)))); return; } if (UserInfoProvider.NameIsReserved(siteName, ui.UserNickName)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName))); return; } #endregion #region "License limitations" string errorMessage = String.Empty; UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage); if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } #endregion // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(userEmail, siteList, 0)) { ShowError(GetString("UserInfo.EmailAlreadyExist")); return; } // Set password UserInfoProvider.SetPassword(ui, passStrength.Text); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EmailTemplateInfo template = null; string emailSubject = null; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject")); } // Send welcome message with username and password, with information that user must be approved by administrator else if (SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject")); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject")); } } if (template != null) { // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required) int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); if (contactId > 0) { ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, MembershipType.CMS_USER, contactId); } // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = ui.Email; email.From = SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress"); email.Subject = emailSubject; try { var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator)); EmailSender.SendEmailWithTemplateText(siteName, email, template, resolver, true); } catch (Exception ex) { EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { ShowError(GetString("RegistrationForm.UserWasNotCreated")); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and e-mail confirmation is not required if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate; if (SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName); } if (mEmailTemplate == null) { // Log missing e-mail template EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress); message.Recipients = ToAddress; message.Subject = GetString("RegistrationForm.EmailSubject"); try { MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui); EmailSender.SendEmailWithTemplateText(siteName, message, mEmailTemplate, resolver, false); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } #endregion #region "Web analytics" // Track successful registration conversion if (TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(siteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument); // Log login activity if (ui.Enabled) { MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument); } } #endregion #region "Roles & authentication" string[] roleList = AssignRoles.Split(';'); foreach (string sn in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, sn); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String s = roleName.StartsWith(".", StringComparison.Ordinal) ? "" : sn; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, s)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, s); } } } } if (DisplayMessage.Trim() != String.Empty) { pnlForm.Visible = false; lblText.Visible = true; lblText.Text = DisplayMessage; } else { if (ui.Enabled) { AuthenticationHelper.AuthenticateUser(ui.UserName, true); } if (RedirectToURL != String.Empty) { URLHelper.Redirect(UrlResolver.ResolveUrl(RedirectToURL)); } else if (QueryHelper.GetString("ReturnURL", "") != String.Empty) { string url = QueryHelper.GetString("ReturnURL", ""); // Do url decode url = Server.UrlDecode(url); // Check that url is relative path or hash is ok if (url.StartsWith("~", StringComparison.Ordinal) || url.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath")) { URLHelper.Redirect(UrlResolver.ResolveUrl(url)); } // Absolute path with wrong hash else { URLHelper.Redirect(AdministrationUrlHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext")); } } } #endregion lblError.Visible = false; } }
/// <summary> /// Sends confirmation or welcome email. /// </summary> private void SendRegistrationEmail(UserInfo ui, string password) { bool error = false; EmailTemplateInfo template = null; // Email message EmailMessage emailMessage = new EmailMessage(); emailMessage.EmailFormat = EmailFormatEnum.Default; emailMessage.Recipients = ui.Email; // Send welcome message with username and password, with confirmation link, user must confirm registration if (ConfirmationRequired) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject"); } // Send welcome message with username and password, with information that user must be approved by administrator else if (SendWelcomeEmail) { if (AdminApprovalRequired) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject"); } } if (template != null) { // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required) int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); if (contactId > 0) { ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, MembershipType.CMS_USER, contactId); } // Prepare resolver for notification and welcome emails MacroResolver resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, password, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, CurrentSiteName, NotifyAdministrator)); emailMessage.From = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSNoreplyEmailAddress")); // Enable macro encoding for body resolver.Settings.EncodeResolvedValues = true; emailMessage.Body = resolver.ResolveMacros(template.TemplateText); // Disable macro encoding for plaintext body and subject resolver.Settings.EncodeResolvedValues = false; emailMessage.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject)); emailMessage.CcRecipients = template.TemplateCc; emailMessage.BccRecipients = template.TemplateBcc; try { EmailHelper.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(CurrentSiteName, emailMessage, true); } catch (Exception ex) { EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { ShowError(GetString("RegistrationForm.UserWasNotCreated")); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); } }
/// <summary> /// Sends confirmation or welcome email. /// </summary> private void SendRegistrationEmail(UserInfo ui) { bool error = false; EmailTemplateInfo template = null; // Email message EmailMessage emailMessage = new EmailMessage(); emailMessage.EmailFormat = EmailFormatEnum.Default; emailMessage.Recipients = ui.Email; emailMessage.From = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSNoreplyEmailAddress"); // Send welcome message with username and password, with confirmation link, user must confirm registration if (ConfirmationRequired) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject"); } // Send welcome message with username and password, with information that user must be approved by administrator else if (SendWelcomeEmail) { if (AdminApprovalRequired) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject"); } } if (template != null) { // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required) int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); if (contactId > 0) { ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, MembershipType.CMS_USER, contactId); } try { // Prepare resolver for notification and welcome emails MacroResolver resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, CurrentSiteName, NotifyAdministrator)); EmailSender.SendEmailWithTemplateText(CurrentSiteName, emailMessage, template, resolver, true); } catch (Exception ex) { EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { ShowError(GetString("RegistrationForm.UserWasNotCreated")); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); } }
/// <summary> /// Sends e-mail with password in case the user has specified his email address. /// Otherwise, displays the newly generated password to the current user. /// </summary> /// <param name="pswd">Password to send</param> private void SendEmail(string pswd) { if (UserInfo == null) { return; } // Check whether the 'From' element was specified string siteName = SiteContext.CurrentSiteName; string emailFrom = SettingsKeyInfoProvider.GetValue("CMSSendPasswordEmailsFrom", siteName); if (string.IsNullOrEmpty(emailFrom)) { ShowError(String.Format("{0} {1}", GetString("Administration-User_Edit_Password.PassChangedNotSent"), GetString("Administration-User_Edit_Password.FromMissing"))); return; } string emailTo = UserInfo.Email; if (!String.IsNullOrEmpty(emailTo)) { EmailMessage em = new EmailMessage { From = emailFrom, Recipients = emailTo, Subject = GetString("Administration-User_Edit_Password.NewGen"), EmailFormat = EmailFormatEnum.Default }; // Get e-mail template - try to get site specific template if edited user is assigned to current site EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("Membership.ChangedPassword", UserInfo.IsInSite(siteName) ? siteName : null); if (template != null) { em.Body = template.TemplateText; // Because the password was generated by the system, it's included in the e-mail MacroResolver resolver = MembershipResolvers.GetPasswordResolver(UserInfo, pswd); try { EmailHelper.ResolveMetaFileImages(em, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); // Send message immediately (+ resolve macros) EmailSender.SendEmailWithTemplateText(siteName, em, template, resolver, true); // Inform on success ShowConfirmation(GetString("Administration-User_Edit_Password.PasswordsSent") + " " + HTMLHelper.HTMLEncode(emailTo)); return; } catch (Exception ex) { EventLogProvider.LogException("PasswordRetrieval", "USERPASSWORD", ex); ShowError("Failed to send the password: "******"Administration-User_Edit_Password.PassChangedNotSent")); } } else { ShowConfirmation(String.Format(GetString("Administration-User_Edit_Password.passshow"), pswd), true); } }
/// <summary> /// Sends e-mail with password if required. /// </summary> /// <param name="subject">Subject of the e-mail sent</param> /// <param name="pswd">Password to send</param> /// <param name="emailType">Type of the e-mail specifying the template used (NEW, CHANGED, RESEND)</param> /// <param name="showPassword">Indicates whether password is shown in message.</param> private void SendEmail(string subject, string pswd, string emailType, bool showPassword) { // Check whether the 'From' element was specified string siteName = SiteContext.CurrentSiteName; string emailFrom = SettingsKeyInfoProvider.GetValue("CMSSendPasswordEmailsFrom", siteName); bool fromMissing = string.IsNullOrEmpty(emailFrom); if ((!string.IsNullOrEmpty(emailType)) && (UserInfo != null) && (!fromMissing)) { string emailTo = UserInfo.Email; if (!String.IsNullOrEmpty(emailTo)) { EmailMessage em = new EmailMessage(); em.From = emailFrom; em.Recipients = emailTo; em.Subject = subject; em.EmailFormat = EmailFormatEnum.Default; string templateName = null; // Get e-mail template name switch (emailType.ToLowerCSafe()) { case "new": templateName = "Membership.NewPassword"; break; case "changed": templateName = "Membership.ChangedPassword"; break; case "resend": templateName = "Membership.ResendPassword"; break; } // Get template info object if (templateName != null) { try { // Get e-mail template - try to get site specific template if edited user is assigned to current site EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate(templateName, UserInfo.IsInSite(siteName) ? siteName : null); if (template != null) { em.Body = template.TemplateText; // Create macro resolver MacroResolver resolver = MembershipResolvers.GetPasswordResolver(UserInfo, pswd); // Add template attachments EmailHelper.ResolveMetaFileImages(em, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); // Send message immediately (+ resolve macros) EmailSender.SendEmailWithTemplateText(siteName, em, template, resolver, true); // Inform on success ShowConfirmation(GetString("Administration-User_Edit_Password.PasswordsSent") + " " + HTMLHelper.HTMLEncode(emailTo)); return; } } catch (Exception ex) { // Log the error to the event log EventLogProvider.LogException("Password retrieval", "USERPASSWORD", ex); ShowError("Failed to send the password: "******"Administration-User_Edit_Password.passshow"), pswd), true); } else { ShowConfirmation(GetString("Administration-User_Edit_Password.PassChangedNotSent")); } return; } } // Inform on error string errorMessage = GetString("Administration-User_Edit_Password.PasswordsNotSent"); if (fromMissing) { errorMessage += " " + GetString("Administration-User_Edit_Password.FromMissing"); } ShowError(errorMessage); }
/// <summary> /// Sets new UserInfo for approved user. /// </summary> /// <param name="userID">User to be approved</param> protected void SetUserInfo(int userID) { UserInfo user = UserInfoProvider.GetFullUserInfo(userID); // Cancel waiting for approval attribute user.UserSettings.UserWaitingForApproval = false; // Set activation time to now user.UserSettings.UserActivationDate = DateTime.Now; // Set user who activated this account user.UserSettings.UserActivatedByUserID = MembershipContext.AuthenticatedUser.UserID; // Enable user user.Enabled = true; UserInfoProvider.SetUserInfo(user); // Send e-mail to user if (!String.IsNullOrEmpty(user.Email)) { EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("RegistrationUserApproved", SiteContext.CurrentSiteName); if (template != null) { string from = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSNoreplyEmailAddress")); if (!String.IsNullOrEmpty(from)) { EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; // Get e-mail sender and subject from template, if used email.From = from; email.Recipients = user.Email; MacroResolver resolver = MembershipResolvers.GetRegistrationApprovalResolver(user, URLHelper.GetAbsoluteUrl("~/")); // Enable encoding of macro results for HTML mail body resolver.Settings.EncodeResolvedValues = true; email.Body = resolver.ResolveMacros(template.TemplateText); // Disable encoding of macro results for plaintext body and subject resolver.Settings.EncodeResolvedValues = false; string emailSubject = EmailHelper.GetSubject(template, GetString("registrationform.registrationapprovalemailsubject")); email.Subject = resolver.ResolveMacros(emailSubject); email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); email.CcRecipients = template.TemplateCc; email.BccRecipients = template.TemplateBcc; try { // Add attachments EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); EmailSender.SendEmail(SiteContext.CurrentSiteName, email); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "WaitingForApprovalEmail"); } } else { EventLogProvider.LogEvent(EventType.ERROR, "WaitingForApproval", "EmailSenderNotSpecified"); } } else { // Log missing e-mail template try { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationUserApproved", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } catch { } } } // User is approved and enabled, could be logged into statistics AnalyticsHelper.LogRegisteredUser(SiteContext.CurrentSiteName, user); }
/// <summary> /// Send e-mail to administrator about new registration. /// </summary> /// <param name="administrationApproval">Indicates if administration approval is required</param> private void SendEmailToAdministrator(bool administrationApproval) { EmailTemplateInfo template = null; MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(RegisteredUser); string currentSiteName = SiteContext.CurrentSiteName; if (administrationApproval) { template = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", currentSiteName); } else { template = EmailTemplateProvider.GetEmailTemplate("Registration.New", currentSiteName); } if (template == null) { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { // E-mail template ok string from = EmailHelper.GetSender(template, (!String.IsNullOrEmpty(FromAddress)) ? FromAddress : SettingsKeyInfoProvider.GetValue(currentSiteName + ".CMSNoreplyEmailAddress")); if (!String.IsNullOrEmpty(from)) { // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = AdministratorEmail; // Get e-mail sender and subject from template, if used email.From = from; // Enable encoding of macro results for HTML mail body resolver.Settings.EncodeResolvedValues = true; email.Body = resolver.ResolveMacros(template.TemplateText); // Disable encoding of macro results for plaintext body and subject resolver.Settings.EncodeResolvedValues = false; email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); string emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.EmailSubject")); email.Subject = resolver.ResolveMacros(emailSubject); email.CcRecipients = template.TemplateCc; email.BccRecipients = template.TemplateBcc; try { EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(currentSiteName, email, true); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationApprovalEmail"); } } else { EventLogProvider.LogEvent(EventType.ERROR, "RegistrationApproval", "EmailSenderNotSpecified"); } } }