public async Task <ReturnStatus> SendVerificationEmailAsync(string emailAddress, string emailView) { ReturnStatus retVal = new ReturnStatus() { IsSuccessful = true, ErrorMessages = new List <string>(), }; IdentityUser user = await UserManager.FindByEmailAsync(emailAddress); if (user == null) { retVal.IsSuccessful = false; retVal.ErrorMessages.Add(ErrorCodeConstants.ERROR_USER_DOES_NOT_EXIST); } else { SendGrid.Response response = await EmailSender.SendEmailAsync(emailAddress, "Hello from ShimMath.com", html : emailView); if (response.StatusCode != System.Net.HttpStatusCode.Accepted) { retVal.IsSuccessful = false; retVal.ErrorMessages.Add(ErrorCodeConstants.ERROR_VERIFICATION_EMAIL_SEND_FAILED); } } return(retVal); }
public bool SetResponse(SendGrid.Response resp) { StatusCode = resp.StatusCode; var ret = JsonConvert.DeserializeObject(resp.Body.ReadAsStringAsync().Result); return(Successful()); }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { ApplicationUser user = await _userManager.FindByEmailAsync(Input.Email); if (user == null) { return(Page()); } string newPass = Guid.NewGuid().ToString(); SendGrid.Response result = await emailsService .SendAsync(user.Email, "New password", $"Your new password is: {newPass}"); if (result.StatusCode.ToString() == "Accepted") { IdentityResult removePassResult = await _userManager.RemovePasswordAsync(user); IdentityResult addPassResult = await _userManager.AddPasswordAsync(user, newPass); if (removePassResult.Succeeded && addPassResult.Succeeded) { TempData["passwordReset"] = true; return(RedirectToPage("./Login")); } } } return(Page()); }
private async Task BuildAndSendEmail(ScheduleSyncSpec s, IEnumerable <ScheduleComparer.CompareResult> res) { EmailAddress from = new EmailAddress("*****@*****.**", "Twin Rinks Schedule Checker"); string subject = $"[{s.TeamSnapTeamName}] {res.Count()} Schedule differences found vs [{s.TwinRinkTeamName}]@TwinRinks.com"; EmailAddress to = new EmailAddress(s.Recipients); StringBuilder mailBuider = new StringBuilder(); string host = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}"; mailBuider.Append($"<p><a href='{host}/CompareSchedule?SelectedTeamSnapTeamId={s.TeamSnapTeamId}&SelectedTwinRinksTeam={s.TwinRinkTeamName}'>Go to Site </a></p>"); mailBuider.Append(HtmlHelperExtentions.ToHtmlTable(null, res, "id", border: 0, actionGenerator: (t) => $"<a href='{host + "/ScheduleSyncSpec/CreateExclusion?Date=" + (t.TR_EventTime.HasValue ? t.TR_EventTime.Value.ToShortDateString() : ScheduleComparer.ToCSTTime(t.TS_EventTime.Value).ToShortDateString())}&SpecID={s.ID}'>Mute</a>")); string htmlContent = mailBuider.ToString(); SendGridMessage msg = MailHelper.CreateSingleEmail(from, to, subject, "", htmlContent); SendGrid.Response response = await _sndGrdClient.SendEmailAsync(msg); if (response.StatusCode != System.Net.HttpStatusCode.Accepted) { throw new Exception(response.StatusCode.ToString()); } }
public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { using (IdentityModels entities = new IdentityModels()) { var userStore = new UserStore <User>(entities); var manager = new UserManager <User>(userStore); manager.UserTokenProvider = new EmailTokenProvider <User>(); var user = new User() { UserName = model.EmailAddress, Email = model.EmailAddress }; IdentityResult result = manager.Create(user, model.Password); if (result.Succeeded) { User u = manager.FindByName(model.EmailAddress); // Creates customer record in Braintree string merchantId = ConfigurationManager.AppSettings["Braintree.MerchantID"]; string publicKey = ConfigurationManager.AppSettings["Braintree.PublicKey"]; string privateKey = ConfigurationManager.AppSettings["Braintree.PrivateKey"]; string environment = ConfigurationManager.AppSettings["Braintree.Environment"]; Braintree.BraintreeGateway braintree = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey); Braintree.CustomerRequest customer = new Braintree.CustomerRequest(); customer.CustomerId = u.Id; customer.Email = u.Email; var r = await braintree.Customer.CreateAsync(customer); string confirmationToken = manager.GenerateEmailConfirmationToken(u.Id); string sendGridApiKey = ConfigurationManager.AppSettings["SendGrid.ApiKey"]; SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridApiKey); SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage(); message.Subject = string.Format("Please confirm your account"); message.From = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey"); message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(model.EmailAddress)); SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/html", string.Format("<a href=\"{0}\">Confirm Account</a>", Request.Url.GetLeftPart(UriPartial.Authority) + "/MyAccount/Confirm/" + confirmationToken + "?email=" + model.EmailAddress)); message.AddContent(contents.Type, contents.Value); SendGrid.Response response = await client.SendEmailAsync(message); return(RedirectToAction("ConfirmSent")); } else { ModelState.AddModelError("EmailAddress", "Unable to register with this email address."); } } } return(View(model)); }
public async System.Threading.Tasks.Task <ActionResult> Register(string username, string email, string password) { var userStore = new Microsoft.AspNet.Identity.EntityFramework.UserStore <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(); var manager = new Microsoft.AspNet.Identity.UserManager <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(userStore); var user = new Microsoft.AspNet.Identity.EntityFramework.IdentityUser() { UserName = username, Email = email, EmailConfirmed = false }; manager.UserTokenProvider = new Microsoft.AspNet.Identity.EmailTokenProvider <Microsoft.AspNet.Identity.EntityFramework.IdentityUser>(); Microsoft.AspNet.Identity.IdentityResult result = await manager.CreateAsync(user, password); if (result.Succeeded) { //I have some options: log them in, or I can send them an email to "Confirm" their account details.' //I don't have email set up this week, so we'll come back to that. string confirmationToken = await manager.GenerateEmailConfirmationTokenAsync(user.Id); string confirmationLink = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/Confirm/" + user.Id + "?token=" + confirmationToken; string apiKey = System.Configuration.ConfigurationManager.AppSettings["SendGrid.ApiKey"]; SendGrid.ISendGridClient client = new SendGrid.SendGridClient(apiKey); SendGrid.Helpers.Mail.EmailAddress from = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Coding Cookware Administrator"); SendGrid.Helpers.Mail.EmailAddress to = new SendGrid.Helpers.Mail.EmailAddress(email); string subject = "Confirm your Coding Cookware Account"; string htmlContent = string.Format("<a href=\"{0}\">Confirm Your Account</a>", confirmationLink); string plainTextContent = confirmationLink; SendGrid.Helpers.Mail.SendGridMessage message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); SendGrid.Response response = await client.SendEmailAsync(message); TempData["EmailAddress"] = email; return(RedirectToAction("ConfirmationSent")); //Commenting this out: I'm not going to log the user in on registration anymore - I'm going to send them a confirmation email instead. //This authentication manager will create a cookie for the current user, and that cookie will be exchanged on each request until the user logs out //var authenticationManager = HttpContext.GetOwinContext().Authentication; //var userIdentity = await manager.CreateIdentityAsync(user, Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie); //authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { }, userIdentity); } else { ViewBag.Error = result.Errors; return(View()); } return(RedirectToAction("Index", "Home")); }
private void InitializeMocks(out Mock <ISendGridClientFactory> factoryMock, out Mock <ISendGridClient> clientMock) { var mockResponse = new SendGrid.Response(HttpStatusCode.OK, null, null); clientMock = new Mock <Client.ISendGridClient>(MockBehavior.Strict); clientMock .Setup(c => c.SendMessageAsync(It.IsAny <SendGridMessage>(), It.IsAny <CancellationToken>())) .ReturnsAsync(mockResponse); factoryMock = new Mock <ISendGridClientFactory>(MockBehavior.Strict); factoryMock .Setup(f => f.Create(It.IsAny <string>())) .Returns(clientMock.Object); }
public void TestGoodRequestButSendGridError() { var stringContent = new StringContent(""); var tempResponse = new HttpResponseMessage(); tempResponse.Headers.Add("deviceId", "1234"); SendGrid.Response response1 = new SendGrid.Response(HttpStatusCode.BadRequest, stringContent, tempResponse.Headers); sendGridClient.Setup(t => t.SendEmail(It.IsAny <SendGridMessage>())).Returns(response1); var request = TestFactory.CreateHttpRequest("{\"Subject\":\"Please Help\",\"Email\":\"[email protected]\",\"Phone\":\"513.204.9321\",\"FullName\":\"Brandon Schenz\",\"Message\":\"I need more info RIGHT away!\"}"); var response = (BadRequestObjectResult)_fixture.Run(request, testLogger); Assert.AreEqual(StatusCodes.Status400BadRequest, response.StatusCode); }
public void TestBadRequest() { var stringContent = new StringContent(""); var tempResponse = new HttpResponseMessage(); tempResponse.Headers.Add("deviceId", "1234"); SendGrid.Response response1 = new SendGrid.Response(HttpStatusCode.Accepted, stringContent, tempResponse.Headers); sendGridClient.Setup(t => t.SendEmail(It.IsAny <SendGridMessage>())).Returns(response1); var request = TestFactory.CreateHttpRequest(""); var response = (BadRequestObjectResult)_fixture.Run(request, testLogger); Assert.AreEqual("Error While Sending Email", response.Value); }
public async Task <HttpStatusCode> SendEmailAsync(string fromEmail, string fromEmailName, string toEmail, string subject, string message) { var sendGridMessage = new SendGridMessage(); sendGridMessage.AddTo(toEmail); sendGridMessage.From = new EmailAddress(fromEmail, fromEmailName); sendGridMessage.Subject = subject; sendGridMessage.HtmlContent = message; SendGrid.ISendGridClient transportWeb = new SendGrid.SendGridClient(_apiKey); SendGrid.Response emailTask = await transportWeb.SendEmailAsync(sendGridMessage); return(emailTask.StatusCode); }
public async Task ResendEmailConfirmationAsync(string emailAddress, Func <string, string, string> generateConfirmationLink, string PathToEmailFile) { try { ApplicationUser user = await UserManager.FindByEmailAsync(emailAddress); if (user != null && !user.EmailConfirmed) { string code = await UserManager.GenerateEmailConfirmationTokenAsync(user); string confirmationLink = generateConfirmationLink(code, user.Id); string body = arrangeEmailTemplateForEmailConfirmation(user.UserName, PathToEmailFile, confirmationLink); SendGrid.Response emailResponse = await EmailSender.SendEmailAsync(emailAddress, "Confirm your email", body); } } catch (Exception ex) { } }
public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { using (IdentityModels entities = new IdentityModels()) { var userStore = new UserStore <User>(entities); var manager = new UserManager <User>(userStore); manager.UserTokenProvider = new EmailTokenProvider <User>(); var user = manager.FindByName(model.Email); // If user has to activate his email to confirm his account, the use code listing below //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) //{ // return Ok(); //} string code = await manager.GeneratePasswordResetTokenAsync(user.Id); string sendGridKey = System.Configuration.ConfigurationManager.AppSettings["SendGrid.ApiKey"]; SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridKey); SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage(); message.Subject = string.Format("Reset Password"); message.From = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey"); message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(model.Email)); SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/html", string.Format("<a href=\"{0}\">Reset Password</a>", Request.Url.GetLeftPart(UriPartial.Authority) + "/MyAccount/ResetPassword/" + code + "?EmailAddress=" + model.Email)); message.AddContent(contents.Type, contents.Value); SendGrid.Response response = await client.SendEmailAsync(message); //await client.SendEmailAsync(user.Id, "Reset Password", $"Please reset your password by using this {code}"); return(RedirectToAction("ResetSent")); } } return(View()); // If we got this far, something failed, redisplay form }
public async Task <IActionResult> CreateNewUser(NewUserModel user) { if (ModelState.IsValid) { _commander.Execute <NewUserAction, NewUserModel>(user); var newUserAction = _commander.GetInstance <NewUserAction>(); if (newUserAction.Result) { SendGrid.Response mailResponse = await EmailService.SendMail <ConfirmMail>(user.Email, user.Name, user.Surname); if (mailResponse.StatusCode == System.Net.HttpStatusCode.Accepted) { TempData["Message"] = "Kaydınız başarıyla oluşturuldu."; TempData["Success"] = true; await SetLoginClaims(user); } else { var body = await mailResponse.Body.ReadAsStringAsync(); TempData["Message"] = "Kaydınız başarıyla oluşturuldu. Doğrulama maili gönderme sırasında hata algılandı. \n" + body; TempData["Success"] = false; } } else { TempData["Message"] = "Kayıt sırasında bir hata oluştu!"; TempData["Success"] = false; } return(RedirectToRoute("homepage")); } else { ViewBag.Message = "Geçersiz CAPTCHA"; ViewBag.Success = false; return(View("SignUp")); } }
public async Task <InvitationDto> CreateInvitationAsync([FromBody] InvitationDto request) { string origin; try { Microsoft.Extensions.Primitives.StringValues origins; Request.Headers.TryGetValue("Origin", out origins); origin = origins[0]; } catch { Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable; throw new ArgumentException("Origin"); } Invitation entity; using (var uow = UowManager.CurrentOrCreateNew(true)) { entity = await InvitationDomainService.CreateAsync(request.MapToEntity()); await uow.CompleteAsync(); } using (var uow = UowManager.CurrentOrCreateNew(true)) { entity = await InvitationDomainService.RetrieveAsync(entity.Id); } SendGrid.Response sendDealerInvitationEmailResponse = await TestDriveEmailService .SendDealerInvitationEmail( new EmailAddress(entity.Email, string.Empty), new DealerInvitationEmailTemplate($"{origin}/#/registration/{entity.InvitationCode}")); InvitationDto dto = new InvitationDto(); dto.MapFromEntity(entity); return(dto); }
public async Task <IActionResult> ContactUs(ContactUsInputModel inputModel) { if (!ModelState.IsValid) { return(View(inputModel)); } SendGrid.Response result = await emailsService .SendAsync(configuration["SendGrid:To"], $"From: {inputModel.Email}", inputModel.Message); if (result.StatusCode.ToString() == "Accepted") { TempData["contact"] = true; return(RedirectToAction(nameof(ContactUs))); } else { TempData["contact"] = false; return(View(inputModel)); } }
public async Task <ActionResult> Index(CheckoutModel model) { if (ModelState.IsValid) { using (AppStoreEntities entities = new AppStoreEntities()) { Order o = null; if (User.Identity.IsAuthenticated) { AspNetUser currentUser = entities.AspNetUsers.Single(x => x.UserName == User.Identity.Name); o = currentUser.Orders.FirstOrDefault(x => x.TimeCompleted == null); if (o == null) { o = new Order(); o.OrderNumber = Guid.NewGuid(); currentUser.Orders.Add(o); entities.SaveChanges(); } } else { if (Request.Cookies.AllKeys.Contains("orderNumber")) { Guid orderNumber = Guid.Parse(Request.Cookies["orderNumber"].Value); o = entities.Orders.FirstOrDefault(x => x.TimeCompleted == null && x.OrderNumber == orderNumber); } if (o == null) { o = new Order(); o.OrderNumber = Guid.NewGuid(); entities.Orders.Add(o); Response.Cookies.Add(new HttpCookie("orderNumber", o.OrderNumber.ToString())); entities.SaveChanges(); } } if (o.OrdersProducts.Sum(x => x.Quantity) == 0) { return(RedirectToAction("Index", "Cart")); } o.BuyerEmail = User.Identity.Name; Address newShippingAddress = new Address(); newShippingAddress.Address1 = model.ShippingAddress1; newShippingAddress.Address2 = model.ShippingAddress2; newShippingAddress.City = model.ShippingCity; newShippingAddress.State = model.ShippingState; newShippingAddress.Zip = model.ZipCode; newShippingAddress.Country = model.ShippingCountry; o.Address1 = newShippingAddress; WhereTo = ("\n Your Order will be shipped to the following address: \n" + model.ShippingAddress1 + "\n " + model.ShippingAddress2 + "\n " + model.ShippingCity + "\n " + model.ShippingState + "\n " + model.ZipCode); entities.sp_CompleteOrder(o.ID); string merchantId = ConfigurationManager.AppSettings["Braintree.MerchantID"]; string publicKey = ConfigurationManager.AppSettings["Braintree.PublicKey"]; string privateKey = ConfigurationManager.AppSettings["Braintree.PrivateKey"]; string environment = ConfigurationManager.AppSettings["Braintree.Environment"]; Braintree.BraintreeGateway braintree = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey); Braintree.TransactionRequest newTransaction = new Braintree.TransactionRequest(); newTransaction.Amount = o.OrdersProducts.Sum(x => x.Quantity * x.Product.Price) ?? 0.01m; Braintree.TransactionCreditCardRequest creditCard = new Braintree.TransactionCreditCardRequest(); creditCard.CardholderName = model.CreditCardName; creditCard.CVV = model.CreditCardVerificationValue; creditCard.ExpirationMonth = model.CreditCardExpiration.Value.Month.ToString().PadLeft(2, '0'); creditCard.ExpirationYear = model.CreditCardExpiration.Value.Year.ToString(); creditCard.Number = model.CreditCardNumber; newTransaction.CreditCard = creditCard; // If the user is logged in, associate this transaction with their account if (User.Identity.IsAuthenticated) { Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Is(User.Identity.Name); var customers = braintree.Customer.Search(search); newTransaction.CustomerId = customers.FirstItem.Id; } Braintree.Result <Braintree.Transaction> result = await braintree.Transaction.SaleAsync(newTransaction); if (!result.IsSuccess()) { ModelState.AddModelError("CreditCard", "Could not authorize payment"); return(View(model)); } string sendGridApiKey = ConfigurationManager.AppSettings["SendGrid.ApiKey"]; SendGrid.SendGridClient client = new SendGrid.SendGridClient(sendGridApiKey); SendGrid.Helpers.Mail.SendGridMessage message = new SendGrid.Helpers.Mail.SendGridMessage(); //TODO: Go into SendGrid and set up a template and insert the if below //message.SetTemplateId("524c7845-3ed9-4d53-81c8-b467443f8c5c"); message.Subject = string.Format("Receipt for order {0}", o.ID); message.From = new SendGrid.Helpers.Mail.EmailAddress("*****@*****.**", "Will Mabrey"); message.AddTo(new SendGrid.Helpers.Mail.EmailAddress(o.BuyerEmail)); string prodcuctsReceipt = "You've Ordered: "; WhatWasOrdered = prodcuctsReceipt; foreach (var item in o.OrdersProducts) { string addition = string.Format("\n " + "{0} copies of {1}", item.Quantity, item.Product.Name); prodcuctsReceipt += addition; } SendGrid.Helpers.Mail.Content contents = new SendGrid.Helpers.Mail.Content("text/plain", string.Format("Thank you for ordering through Ye Olde App Store \n {0} {1}", prodcuctsReceipt, WhereTo)); message.AddSubstitution("%ordernum%", o.ID.ToString()); message.AddContent(contents.Type, contents.Value); SendGrid.Response response = await client.SendEmailAsync(message); o.TimeCompleted = DateTime.UtcNow; entities.SaveChanges(); } return(RedirectToAction("profile", "Home")); } return(View(model)); }