Beispiel #1
0
        /// <summary>
        /// Sends e-mail to the receiver(s). Multiple receivers shall be seperated with ';'
        /// </summary>
        /// <param name="email">E-mail to be sent</param>
        public void SendEMail(EMail email)
        {
            var validator = new EmailAddressValidator(_resourceManager);

            using (SmtpClient smtpClient = new SmtpClient(email.SmtpHostAddress, email.SmtpPort))
            {
                smtpClient.Timeout     = email.SmtpClientTimeOut;
                smtpClient.EnableSsl   = email.SmtpEnableSsl;
                smtpClient.Credentials = new NetworkCredential(email.SmtpUserName, email.SmtpPassword);

                MailMessage mailMessage = new MailMessage();
                mailMessage.From       = new MailAddress(email.FromAddress, email.FromName);
                mailMessage.Body       = email.Body;
                mailMessage.Subject    = email.Subject;
                mailMessage.IsBodyHtml = true;
                mailMessage.Priority   = MailPriority.Normal;
                mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

                foreach (string to in email.Receivers.Split(','))
                {
                    if (validator.Validate(to).Succeeded)
                    {
                        mailMessage.To.Add(to);
                    }
                    else
                    {
                        throw new ASException(string.Join(".", validator.Validate(to).Errors));
                    }
                }
                Task.Factory.StartNew(() => smtpClient.Send(mailMessage))
                .TimeoutAfter(email.SmtpClientTimeOut)
                .Wait();
            }
        }
Beispiel #2
0
        public async Task InviteUserAsync(Guid inviterId, string invitedEmail)
        {
            ValidationResult result = new EmailAddressValidator()
                                      .Validate(new EmailAddress(invitedEmail));

            if (!result.IsValid)
            {
                foreach (ValidationFailure failure in result.Errors)
                {
                    AddNotification(failure.ErrorCode, failure.ErrorMessage);
                }

                return;
            }

            NutrientIdentityUser inviter = await _userManager.FindByIdAsync(inviterId.ToString());

            NutrientIdentityUser invited = await _userManager.FindByEmailAsync(invitedEmail);

            if (invited != null)
            {
                AddNotification("Usuário já existe", "O usuário já está cadastrado na rede Nutrient.");
            }
            else
            {
                EmailTemplate emailTemplate = new EmailTemplate()
                                              .SetTo(invitedEmail)
                                              .SetTemplate(TemplateTypes.UserInvitationTemplateId)
                                              .AddSubstitution("-inviterName-", inviter.Name)
                                              .AddSubstitution("-inviterEmail-", inviter.Email)
                                              .AddSubstitution("-invitedEmail-", invitedEmail);

                await _emailDispatcher.SendEmailAsync(emailTemplate);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Validates the mail.
        /// </summary>
        /// <param name="mail">The mail.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static MailAdressStatus ValidateMail(string mail)
        {
            var valid = MailAdressStatus.ProbablyGood;

            try
            {
                var validator = new EmailAddressValidator("MN110-1C20DF387EA9952F661A118648FA-468F");

                // To perform DNS MX lookup queries, we need some DNS servers for that.
                validator.DnsServers.Autodetect();

                var result = validator.Verify(mail);

                switch (result)
                {
                case AddressValidationLevel.OK:
                    valid = MailAdressStatus.Good; break;

                case AddressValidationLevel.RegexCheck:
                    valid = MailAdressStatus.Bad; break;

                case AddressValidationLevel.DnsQuery:
                case AddressValidationLevel.SendAttempt:
                case AddressValidationLevel.SmtpConnection:
                    valid = MailAdressStatus.ProbablyGood; break;
                }
            }
            catch (Exception ex)
            {
                // ignored
            }
            return(valid);
        }
        public void ValidateEmailAddress(string address, bool isValid)
        {
            // Arrange
            var emailAddressValidator = new EmailAddressValidator();

            // Act & Assert
            Assert.Equal(isValid, emailAddressValidator.Validate(address));
        }
 public void IfIsNotValidEmailAddress(string emailAddress, string argumentName, EmailAddressValidator.Options validatorOptions, string message = null)
 {
     if (!EmailAddressValidator.Validate(emailAddress, validatorOptions))
     {
         var exceptionMsg = message ?? string.Format(DefaultIfIsNotValidEmailAddressMessage, emailAddress);
         throw new ArgumentException(exceptionMsg, argumentName);
     }
 }
 public void IfIsNotValidEmailAddress(string emailAddress, EmailAddressValidator.Options validatorOptions)
 {
     if (!EmailAddressValidator.Validate(emailAddress, validatorOptions))
     {
         var exceptionMsg = string.Format(DefaultIfIsNotValidEmailAddressMessage, emailAddress);
         throw new ArgumentException(exceptionMsg);
     }
 }
Beispiel #7
0
        /// <inheritdoc cref="BaseFilterFormatter.FormatPropertyName"/>
        protected override string FormatPropertyName(string obj, PropertyDefinition propertyDefinition)
        {
            if (EmailAddressValidator.IsValid(obj))
            {
                return($"{propertyDefinition.Name}/EmailAddress/Address");
            }

            return($"{propertyDefinition.Name}/EmailAddress/Name");
        }
Beispiel #8
0
        public void EmailValidator_Should_Return_Valid(string email)
        {
            Mock <IResourceManager> mockResourceManager = new Mock <IResourceManager>();

            mockResourceManager.Setup(m => m.GetString(It.IsAny <string>())).Returns(string.Empty);
            EmailAddressValidator validator = new EmailAddressValidator(mockResourceManager.Object);

            Assert.True(validator.Validate(email).Succeeded);
        }
        public void Invalid(string value)
        {
            IValidator <EmailAddress> validator = new EmailAddressValidator();

            var target = new ValidationTarget <EmailAddress>(new EmailAddress(value));

            validator.Validate(target);
            Assert.True(target.GetResult().HasErrors);
        }
Beispiel #10
0
        public void EmailAddressValidator()
        {
            var validator = _serviceProvider.GetService <IValidator>();

            _testLeadEntity.Properties = new IProperty[] { new DefaultProperty(Modules.LeadEntity.Interface.Constants.PropertyKeys.EmailAddressKey, "*****@*****.**") };
            var address = new EmailAddressValidator();

            address.ValidLead(_testLeadEntity);

            bool expectedValue = false;

            var actualValue = validator.ValidLead(_testLeadEntity);

            Assert.AreEqual(expectedValue, actualValue);
        }
Beispiel #11
0
        public IActionResult EnqueueEmailV1([FromBody] EmailV1 model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!EmailAddressValidator.IsValidFormat(model.ToEmail))
            {
                ModelState.AddModelError(MessageType.EmailInvalid.ToString(), model.ToEmail);
                return(BadRequest(ModelState));
            }

            var email = map.Map <uvw_EmailQueue>(model);

            uow.EmailQueue.Create(email);
            uow.Commit();

            return(NoContent());
        }
Beispiel #12
0
        public EmailValidator()
        {
            var emailAddressValidator = new EmailAddressValidator();

            this.ValidationExpression = emailAddressValidator.GetValidationRegExString();
        }
Beispiel #13
0
        public void btnUpdateAccount_Click(object sender, EventArgs e)
        {
            ctrlAccount.PasswordValidate        = ctrlAccount.Password;
            ctrlAccount.PasswordConfirmValidate = ctrlAccount.PasswordConfirm;
            ctrlAccount.Over13   = ctrlAccount.Over13;
            lblErrorMessage.Text = String.Empty;
            pnlErrorMsg.Visible  = false;
            Page.Validate("account");
            if (Page.IsValid)
            {
                String EMailField = ctrlAccount.Email.ToLowerInvariant().Trim();
                NewEmailAddressAllowed = Customer.NewEmailPassesDuplicationRules(EMailField, ThisCustomer.CustomerID, false);

                bool emailisvalid = new EmailAddressValidator().IsValidEmailAddress(EMailField);
                if (!emailisvalid)
                {
                    lblAcctUpdateMsg.Text = AppLogic.GetString("createaccount.aspx.17", SkinID, ThisCustomer.LocaleSetting);
                }

                if (!NewEmailAddressAllowed || !emailisvalid)
                {
                    EMailField = ThisCustomer.EMail;                     // preserve the old email but go ahead and update their account with other changes below
                }


                string pwd     = null;
                object saltkey = null;
                if (ctrlAccount.Password.Trim().Length > 0)
                {
                    Password p = new Password(ctrlAccount.Password);
                    pwd     = p.SaltedPassword;
                    saltkey = p.Salt;
                }
                bool HasActiveRecurring = ThisCustomer.HasActiveRecurringOrders(true);

                ctrlAccount.ShowSaveCCNote = false;


                if (!ctrlAccount.SaveCC && (HasActiveRecurring && !AppLogic.AppConfigBool("Recurring.UseGatewayInternalBilling")))
                {
                    ctrlAccount.SaveCC         = true;
                    ctrlAccount.ShowSaveCCNote = true;
                }

                String vtr = ctrlAccount.VATRegistrationID;
                if (!AppLogic.AppConfigBool("VAT.Enabled"))
                {
                    vtr = null;
                    ctrlAccount.ShowVATRegistrationIDInvalid = false;
                    ctrlAccount.VATRegistrationID            = String.Empty;
                }
                else
                {
                    Exception vatServiceException;
                    Boolean   vatIsValid = AppLogic.VATRegistrationIDIsValid(ThisCustomer, vtr, out vatServiceException);
                    if (ctrlAccount.VATRegistrationID.Length == 0 || vatIsValid)
                    {
                        ctrlAccount.ShowVATRegistrationIDInvalid = false;
                    }
                    else
                    {
                        if (vatServiceException != null && vatServiceException.Message.Length > 0)
                        {
                            if (vatServiceException.Message.Length > 255)
                            {
                                lblErrorMessage.Text = Server.HtmlEncode(vatServiceException.Message.Substring(0, 255));
                            }
                            else
                            {
                                lblErrorMessage.Text = Server.HtmlEncode(vatServiceException.Message);
                            }
                        }
                        else
                        {
                            lblErrorMessage.Text = "account.aspx.91".StringResource();
                        }

                        pnlErrorMsg.Visible = lblErrorMessage.Text.Length > 0;

                        vtr = null;
                        ctrlAccount.ShowVATRegistrationIDInvalid = true;
                        ctrlAccount.VATRegistrationID            = String.Empty;
                    }
                }

                string strDOB = null;
                if (AppLogic.AppConfigBool("Account.ShowBirthDateField"))
                {
                    strDOB = ctrlAccount.DOBMonth + "/" + ctrlAccount.DOBDay + "/" + ctrlAccount.DOBYear;
                }
                ThisCustomer.UpdateCustomer(
                    /*CustomerLevelID*/ null,
                    /*EMail*/ EMailField,
                    /*SaltedAndHashedPassword*/ pwd,
                    /*SaltKey*/ saltkey,
                    /*DateOfBirth*/ strDOB,
                    /*Gender*/ null,
                    /*FirstName*/ ctrlAccount.FirstName,
                    /*LastName*/ ctrlAccount.LastName,
                    /*Notes*/ null,
                    /*SkinID*/ null,
                    /*Phone*/ ctrlAccount.Phone,
                    /*AffiliateID*/ null,
                    /*Referrer*/ null,
                    /*CouponCode*/ null,
                    /*OkToEmail*/ CommonLogic.IIF(ctrlAccount.OKToEmailYes, 1, 0),
                    /*IsAdmin*/ null,
                    /*BillingEqualsShipping*/ null,
                    /*LastIPAddress*/ null,
                    /*OrderNotes*/ null,
                    /*SubscriptionExpiresOn*/ null,
                    /*RTShipRequest*/ null,
                    /*RTShipResponse*/ null,
                    /*OrderOptions*/ null,
                    /*LocaleSetting*/ null,
                    /*MicroPayBalance*/ null,
                    /*RecurringShippingMethodID*/ null,
                    /*RecurringShippingMethod*/ null,
                    /*BillingAddressID*/ null,
                    /*ShippingAddressID*/ null,
                    /*GiftRegistryGUID*/ null,
                    /*GiftRegistryIsAnonymous*/ null,
                    /*GiftRegistryAllowSearchByOthers*/ null,
                    /*GiftRegistryNickName*/ null,
                    /*GiftRegistryHideShippingAddresses*/ null,
                    /*CODCompanyCheckAllowed*/ null,
                    /*CODNet30Allowed*/ null,
                    /*ExtensionData*/ null,
                    /*FinalizationData*/ null,
                    /*Deleted*/ null,
                    /*Over13Checked*/ CommonLogic.IIF(ctrlAccount.Over13, 1, 0),
                    /*CurrencySetting*/ null,
                    /*VATSetting*/ null,
                    /*VATRegistrationID*/ vtr,
                    /*StoreCCInDB*/ CommonLogic.IIF(ctrlAccount.SaveCC, 1, 0),
                    /*IsRegistered*/ null,
                    /*LockedUntil*/ null,
                    /*AdminCanViewCC*/ null,
                    /*BadLogin*/ null,
                    /*Active*/ null,
                    /*PwdChangeRequired*/ null,
                    /*RegisterDate*/ null,
                    /*StoreId*/ null
                    );

                AccountUpdated = true;
            }
            RefreshPage();
        }
 public void IsTrue_WhenEmailIsCorrect(string emailAddress)
 {
     Assert.True(EmailAddressValidator.IsValid(emailAddress));
 }
 public EmailAddressValidatorTest()
 {
     validator = new EmailAddressValidator();
 }
 public void TestThrowsExceptionIfNull()
 {
     Assert.Throws <ArgumentNullException>(() => EmailAddressValidator.Validate(null, EmailAddressValidator.Options.AllowInternational | EmailAddressValidator.Options.AllowTopLevelDomains), "Null Address");
 }
 public void IsFalse_WhenEmailIsIncorrect(string emailAddress)
 {
     Assert.False(EmailAddressValidator.IsValid(emailAddress));
 }
Beispiel #18
0
            public void InstantiateIn(System.Web.UI.Control container)
            {
                switch (templateType)
                {
                case DataControlRowType.Header:
                    // build the header for this column
                    Label lc = new Label();
                    //lc.Text = "<b>" + BreakCamelCase(columnName) + "</b>";
                    lc.Text = "<b>" + columnName + "</b>";
                    container.Controls.Add(lc);
                    break;

                case DataControlRowType.DataRow:
                    // build one row in this column
                    Label l = new Label();
                    // register an event handler to perform the data binding
                    l.DataBinding += new EventHandler(this.msg_DataBinding);
                    container.Controls.Add(l);

                    var    user      = AbleContext.Current.User;
                    string emailText = string.Empty;
                    if (user != null && !user.IsAnonymous)
                    {
                        emailText = AbleContext.Current.User.Email;
                    }

                    string  validatorId = Guid.NewGuid().ToString();
                    TextBox emailbox    = new TextBox();
                    emailbox.ID              = "EmailText";
                    emailbox.SkinID          = "NotifyEmail";
                    emailbox.ValidationGroup = "RestockNotify" + validatorId;
                    emailbox.Text            = emailText;

                    LinkButton notify = new LinkButton();
                    notify.ID              = "Notify";
                    notify.Text            = "Notify";
                    notify.CommandName     = "NotifyMe";
                    notify.CssClass        = "button linkButton";
                    notify.ValidationGroup = "RestockNotify" + validatorId;
                    notify.DataBinding    += new EventHandler(this.btn_DataBinding);

                    EmailAddressValidator emailRequired = new EmailAddressValidator();
                    emailRequired.ID = "UserEmailValidator";
                    emailRequired.ControlToValidate = "EmailText";
                    emailRequired.Required          = true;
                    emailRequired.ErrorMessage      = "Email address should be in the format of [email protected].";
                    emailRequired.Text            = "Email address should be in the format of [email protected].";
                    emailRequired.ValidationGroup = "RestockNotify" + validatorId;

                    HtmlTable tableNotify = new HtmlTable();
                    tableNotify.Border = 0;

                    HtmlTableRow  row  = new HtmlTableRow();
                    HtmlTableCell cell = new HtmlTableCell();
                    cell.Style.Add("padding", "0");
                    cell.Style.Add("border", "none");
                    cell.Controls.Add(emailbox);
                    row.Cells.Add(cell);

                    cell = new HtmlTableCell();
                    cell.Style.Add("padding", "0");
                    cell.Style.Add("border", "none");
                    cell.Controls.Add(notify);
                    row.Cells.Add(cell);

                    HtmlTableRow row2 = new HtmlTableRow();
                    cell = new HtmlTableCell();
                    cell.Style.Add("padding", "0");
                    cell.Style.Add("border", "none");
                    cell.Controls.Add(emailRequired);
                    cell.ColSpan = 2;
                    row2.Cells.Add(cell);

                    tableNotify.Rows.Add(row);
                    tableNotify.Rows.Add(row2);
                    tableNotify.Attributes.Add("style", "display:none;");
                    container.Controls.Add(tableNotify);

                    container.Controls.Add(new LiteralControl("<br />"));

                    Label messageLabel = new Label();
                    messageLabel.ID       = "messageLabel";
                    messageLabel.CssClass = "goodCondition";
                    messageLabel.Text     = "Restock notification will be sent to '{0}' <br />";
                    messageLabel.Visible  = false;
                    container.Controls.Add(messageLabel);

                    LinkButton button = new LinkButton();
                    button.ID              = "NotificationLink";
                    button.CssClass        = "linkButton";
                    button.OnClientClick   = "return ShowNotification(this);";
                    button.Text            = AbleContext.Current.Store.Settings.InventoryRestockNotificationLink;
                    button.EnableViewState = false;
                    container.Controls.Add(button);

                    break;

                default:
                    break;
                }
            }