Пример #1
0
        private async Task EnviarEmailDeConfirmacaoDeRegistro(UsuarioADE usuario)
        {
            var codigo = await GerarCodigoDeConfirmacao(usuario);

            var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { usuario = usuario.Email, codigo }, protocol: HttpContext.Request.Scheme);
            string EmailMarkup = await FormatarEmailRegistro(callbackUrl, usuario.Email);

            await _emailSender.SendEmailAsync(usuario.Email, "Confirme sua conta", EmailMarkup);
        }
Пример #2
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                UserApp user = new UserApp()
                {
                    Email = model.Email, UserName = model.Username, Country = model.Country
                };
                user.Token = TokenGenerator.Generate();
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);

                    AuthMessageSender sender  = new AuthMessageSender();
                    string            baseUrl = $"{this.Request.Scheme}://{this.Request.Host}/";
                    string            url     = baseUrl + "EmailConfirmed/" + user.Token;
                    string            message = EmailMessageGenerator.GenerateEmailConfirmMessage(url);

                    sender.SendEmailAsync(user.Email, "Please confirm your email", message);
                    return(Redirect(baseUrl));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Пример #3
0
        private async Task SendEmail(ApplicationUser user, List <Ticket> tickets, PredsGame game)
        {
            emailSecret = Configuration["EmailSecrets:Email"];
            password    = Configuration["EmailSecrets:Password"];
            EmailSettings es = new EmailSettings()
            {
                PrimaryDomain    = "smtp.gmail.com",
                PrimaryPort      = 587,
                SecondayDomain   = "smtp.gmail.com",
                SecondaryPort    = 587,
                UsernameEmail    = emailSecret,
                UsernamePassword = password,
                FromEmail        = "*****@*****.**",
                ToEmail          = user.Email
            };
            string email = user.Email;
            string title = "7Element Tickets";
            string body  = $"<h2>Dear {user.FirstName} {user.LastName},</h2><br>" +
                           $"<p>Congrats you have won {tickets.Count} tickets:</p><br><ol>";

            for (int i = 0; i < tickets.Count; i++)
            {
                body += $"<li>Section {tickets[i].Section} Row {tickets[i].Row} Seat {tickets[i].Seat}</li>";
            }
            body += $"</ol><p>For the Nashville Predators game on the {game.DateTime} vs the {game.Opponent}. </p><br>" +
                    "<h3>Thank you,</h3>" +
                    "<h2>7Element</h2>";
            AuthMessageSender ams = new AuthMessageSender(Options.Create(es));
            await ams.SendEmailAsync(email, title, body);
        }
        public async Task <IActionResult> Create(DonatedTicketsCreateViewModel dtcvm)
        {
            ModelState.Remove("DonatedTickets.UserId");
            ModelState.Remove("DonatedTickets.User");
            ModelState.Remove("DonatedTickets.PredsGame");
            for (int i = 0; i < dtcvm.Tickets.Count; i++)
            {
                ModelState.Remove($"Tickets[{i}].DonatedTickets");
            }
            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(HttpContext.User);

                dtcvm.DonatedTickets.User   = user;
                dtcvm.DonatedTickets.UserId = user.Id;
                _context.Add(dtcvm.DonatedTickets);
                await _context.SaveChangesAsync();

                foreach (var ticket in dtcvm.Tickets)
                {
                    ticket.DonatedTicketsId = dtcvm.DonatedTickets.DonatedTicketsId;
                    _context.Add(ticket);
                }
                await _context.SaveChangesAsync();

                emailSecret = Configuration["EmailSecrets:Email"];
                password    = Configuration["EmailSecrets:Password"];
                EmailSettings es = new EmailSettings()
                {
                    PrimaryDomain    = "smtp.gmail.com",
                    PrimaryPort      = 587,
                    SecondayDomain   = "smtp.gmail.com",
                    SecondaryPort    = 587,
                    UsernameEmail    = emailSecret,
                    UsernamePassword = password,
                    FromEmail        = "*****@*****.**",
                    ToEmail          = user.Email
                };
                string email = user.Email;
                string title = "7Element Donation";
                string body  = $"<h2>Dear {user.FirstName} {user.LastName},</h2><br>" +
                               $"<p>This email is to confirm your desired donation to for the following {dtcvm.NumberOfTickets} tickets:</p><br><ol>";
                for (int i = 0; i < dtcvm.Tickets.Count; i++)
                {
                    body += $"<li>Section {dtcvm.Tickets[i].Section} Row {dtcvm.Tickets[i].Row} Seat {dtcvm.Tickets[i].Seat}</li>";
                }
                body += "</ol><p>To complete your donation please dontate the tickets to tickemaster with the username [email protected].</p><br>" +
                        "<h3>Thank you,</h3>" +
                        "<h2>7Element</h2>";
                AuthMessageSender ams = new AuthMessageSender(Options.Create(es));
                await ams.SendEmailAsync(email, title, body);

                return(RedirectToAction(nameof(Confirmation)));
            }
            ViewData["PredsGameId"] = new SelectList(_context.PredsGame, "PredsGameId", "PredsGameId", dtcvm.DonatedTickets.PredsGameId);
            return(View());
        }
Пример #5
0
        public async Task <ActionResult> SendTestMail(SendEMailViewModel model)
        {
            var message = await EMailTemplate("WelcomeEmail");

            message = message.Replace("@ViewBag.Name", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(model.FirstName));

            AuthMessageSender sender = new AuthMessageSender(_hostingEnvironment);
            await sender.SendEmailAsync(model.Email, "Welcome!", message);

            return(View("ConfirmationEmailSent"));
        }
 public async Task MyMethodAsync()
 {
     var eEmailSettings = new EmailSettings()
     {
         CcEmail          = "",
         FromEmail        = "",
         PrimaryDomain    = "smtp.gmail.com",
         PrimaryPort      = 587,
         SecondaryPort    = 0,
         SecondayDomain   = "",
         ToEmail          = "*****@*****.**",
         UsernameEmail    = SenderEmail,
         UsernamePassword = SenderPassword
     };
     var emailSender = new AuthMessageSender(eEmailSettings);
     await emailSender.SendEmailAsync("", "Result file for job ", "Please see attached file.", null);
 }
Пример #7
0
        public async Task <IActionResult> RegistrarAdministrador(RegistroAdmin registro)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View("Index", registro));
                }
                UsuarioADE usuarioCriado = new UsuarioADE()
                {
                    UserName     = registro.Nome,
                    Email        = registro.Email,
                    PasswordHash = GenerateRandomPassword(),
                    IdCurso      = 0
                };
                UsuarioADE agente = await ObterUsuarioLogado();

                var result = await RegistrarUsuarioAdministrador(agente, usuarioCriado, registro.Funcao, registro.Existente);

                if (result.Succeeded)
                {
                    var codigo = await GerarCodigoDeConfirmacao(usuarioCriado);

                    var    callbackUrl = Url.Action("ConfirmEmail", "Account", new { usuario = usuarioCriado, codigo }, protocol: HttpContext.Request.Scheme);
                    string EmailMarkup = await FormatarEmailRegistro(callbackUrl, usuarioCriado.Email, usuarioCriado.PasswordHash);

                    await _emailSender.SendEmailAsync(registro.Email, "ADE - Um perfil foi criado para você", EmailMarkup);
                    await ConfirmarEmail(usuarioCriado, codigo);

                    ViewBag.Retorno = $"Usuário {registro.Funcao} - {usuarioCriado.Email} criado com sucesso";
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            catch (Exception ex)
            {
                await LogError(ex.Message, ex.Source, Dominio.Models.Enums.EnumTipoLog.RegistroDeAdministrador);
            }
            return(View("Index", registro));
        }
Пример #8
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);
                    AuthMessageSender sender = new AuthMessageSender();
                    await sender.SendEmailAsync(Input.Email, "Confirm your email",
                                                $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    // await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    var profileId = profileService.CreateProfile(user.Id);
                    user.ProfileId = profileId;
                    userService.AddUserRole(user.Id, "7b7bb137-36a0-42fa-a59c-622e3e209d37");
                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Пример #9
0
        public void Generate()
        {
            EmailSettings appSettings = new EmailSettings()
            {
                PrimaryDomain    = "smtp.gmail.com",
                PrimaryPort      = 587,
                SecondayDomain   = "smtp.live.com",
                SecondaryPort    = 587,
                UsernameEmail    = "*****@*****.**",
                UsernamePassword = "******",
                FromEmail        = "*****@*****.**",
                ToEmail          = "*****@*****.**",
                CcEmail          = ""
            };
            IOptions <EmailSettings> options = Options.Create(appSettings);
            AuthMessageSender        mail    = new AuthMessageSender(options);

            mail.SendEmailAsync("*****@*****.**", "Test sender", "Test");
        }
Пример #10
0
        public async Task SendNotifyVolunteersCommandWhenInvokingSendEmailAsync()
        {
            const string emailRecipient = "*****@*****.**";
            const string emailSubject   = "test subject";
            const string emailMessage   = "test message body";

            var mediator      = MockIMediator();
            var messageSender = new AuthMessageSender(mediator.Object, Mock.Of <IQueueStorageService>());
            await messageSender.SendEmailAsync(emailRecipient, emailSubject, emailMessage);

            mediator.Verify(mock => mock.SendAsync(
                                It.Is <NotifyVolunteersCommand>(request =>
                                                                request.ViewModel.EmailMessage == emailMessage &&
                                                                request.ViewModel.EmailRecipients.SequenceEqual(new List <string> {
                emailRecipient
            }) &&
                                                                request.ViewModel.HtmlMessage == emailMessage &&
                                                                request.ViewModel.Subject == emailSubject)),
                            Times.Exactly(1));
        }
Пример #11
0
        public void SendEmailAsyncShouldPutCommandOnBus()
        {
            const string emailRecipient = "*****@*****.**";
            const string emailSubject   = "test subject";
            const string emailMessage   = "test message body";

            var bus           = MockIMediator();
            var messageSender = new AuthMessageSender(bus.Object);

            messageSender.SendEmailAsync(emailRecipient, emailSubject, emailMessage);

            bus.Verify(mock => mock.Send(
                           It.Is <NotifyVolunteersCommand>(request =>
                                                           request.ViewModel.EmailMessage == emailMessage &&
                                                           request.ViewModel.EmailRecipients.SequenceEqual(new List <string> {
                emailRecipient
            }) &&
                                                           request.ViewModel.HtmlMessage == emailMessage &&
                                                           request.ViewModel.Subject == emailSubject)),
                       Times.Exactly(1));
        }
Пример #12
0
        public async Task SendEmail(string actionName, string controllerName, ApplicationUser user, string email, string emailTemplate, string emailSubject)
        {
            string code = null;

            if (codeType == "EmailConfirmation")
            {
                code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            }
            else if (codeType == "ResetPassword")
            {
                code = await _userManager.GeneratePasswordResetTokenAsync(user);
            }
            var callbackUrl = Url.Action(actionName, controllerName, new { userId = user.Id, date = DateTime.Now, code = code }, protocol: Context.Request.Scheme);
            var message     = await EMailTemplate(emailTemplate);

            message = message.Replace("@ViewBag.Name", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(user.FirstName));
            message = message.Replace("@ViewBag.Link", callbackUrl);

            AuthMessageSender sender = new AuthMessageSender(_hostingEnvironment);
            await sender.SendEmailAsync(email, emailSubject, message);
        }
Пример #13
0
        public ActionResult ForgotPassword(LostPasswordModel model)
        {
            //Boolean ErrorFlag = false; //unused


            if (TryValidateModel(model))
            {
                var messageService = new AuthMessageSender();
                var userService    = new User.UserService();
                var newPassword    = userService.ResetUserPassword(model.Email);
                var sentmessage    = messageService.SendEmailAsync(model.Email, "Reset IRIS Password", "Hello " + model.Email + " your temporary password is " + newPassword);

                if (!sentmessage)
                {
                    //ErrorFlag = true;
                    ModelState.AddModelError(string.Empty, "SMTP server is down, unable to send temporary password at this time.");

                    return(View("ForgotPassword", model));
                }

                else
                {
                    Session["ExpirationTime"] = DateTime.Now.AddHours(4);

                    return(View("ForgotPasswordConfirmation"));
                }
                //return RedirectToAction("ForgotPasswordConfirmation"); //unreachable
            }



            else
            {
                return(View("Login"));
            }
        }
Пример #14
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null) //|| !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    return(View("ForgotPasswordConfirmation"));
                }

                var token = await _userManager.GeneratePasswordResetTokenAsync(user);

                AuthMessageSender authMessage = new AuthMessageSender();
                string            header      = "Reset Password";
                var callbackUrl = Url.Action("ResetPassword", "User", new { userId = user.Id, token = token }, protocol: HttpContext.Request.Scheme);

                string message = EmailMessageGenerator.GenerateResetPasswordMessage(callbackUrl);
                await authMessage.SendEmailAsync(model.Email, "Reset Password", message);

                return(View("ForgotPasswordConfirmation"));
            }
            return(View(model));
        }
Пример #15
0
        public IActionResult Index()
        {
            var x = _configuration["Serilog:ConnectionString"];
            var y = _cryptographyCertificate.FindValue;
            var z = _configuration["CryptographyCertificate:FindValue"];
            var t = _appOptions.Window.Height;

            var cryptographyCertificate = _configuration.GetSection("CryptographyCertificate").Get <CryptographyCertificate>();
            var findValue = cryptographyCertificate.FindValue;

            //_serilogLogger.ForContext("User", "Aditya").ForContext("Other", "HomeController").Information("Data Added Successfully");

            //_logger.LogDebug("Index page says hello");
            _logger.LogInformation(1001, "Index page says hello");
            //_logger.LogWarning("Index page says hello");
            //_logger.LogError("Index page says hello");
            //_logger.LogCritical("Index page says hello");

            var parameters = new Dictionary <string, object>();
            var parameter1 = new
            {
                Id        = Guid.NewGuid(),
                FirstName = "FN",
                LastName  = "LN",
                Address   = new
                {
                    AddressLine1 = "Yellow 5",
                    City         = "London",
                    PostCode     = "A1N L35",
                    Country      = "UK"
                }
            };

            parameters.Add("parameter1", JsonConvert.SerializeObject(parameter1, Formatting.Indented));

            var parameter2 = 5;

            parameters.Add("parameter2", parameter2);

            var parameter3 = DateTime.Today;

            parameters.Add("parameter3", parameter3);

            //_logger.LogCritical(new Exception("Test error"), "LogCriticalTest", parameters);

            try
            {
                var sender = new AuthMessageSender();
                sender.SendEmailAsync("", "", "");
            }
            catch (Exception ex)
            {
                XmlDocument log4netConfig = new XmlDocument();
                log4netConfig.Load(System.IO.File.OpenRead("log4net.config"));

                var repo = log4net.LogManager.CreateRepository(
                    Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

                log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
                log.Fatal("LOG4NET Send email error", ex);

                _logger.LogError(0, ex, "Send email error");
                _logger.LogCritical(ex, "Send email error", parameters);

                nlog.Fatal(ex, "NLOG Send email error {0}", parameter1.FirstName);

                var person = new Person {
                    FirstName = "Richrad", LastName = "Castle"
                };
                var book = new Book {
                    Author = "Dominik Dan", Title = "Basnik"
                };
                //nlog.Fatal<Person, Book>("NLOG Fatal with 2 classes", person, book);
            }

            return(View());
        }
Пример #16
0
 public async void IsSending()
 {
     await authMessage.SendEmailAsync("*****@*****.**", "blah", "blah-blah-blah");
 }