示例#1
0
        public async Task SendWithEmbeddedImages(string to, string subject, string view, string from = null)
        {
            var builder = new BodyBuilder();
            var model   = new EmailModel {
                Title = "Embedded Images Title"
            };
            var image = builder.LinkedResources.Add(_environment.ContentRootPath + "/Emails/images/logo.png");

            image.ContentId = MimeUtils.GenerateMessageId();
            model.LogoImage = $"cid:{image.ContentId}";

            string html = await _renderer.RenderViewToStringAsync($"/Emails/{view}.cshtml", model);

            builder.HtmlBody = html;

            // create message
            var email = new MimeMessage();

            email.From.Add(MailboxAddress.Parse(from ?? _smtpSettings.FromEmail));
            email.To.Add(MailboxAddress.Parse(to));
            email.Subject = subject;
            email.Body    = builder.ToMessageBody();

            // send email
            using var smtp = new SmtpClient();
            await smtp.ConnectAsync(_smtpSettings.Server, _smtpSettings.Port, SecureSocketOptions.StartTls);

            await smtp.AuthenticateAsync(_smtpSettings.Username, _smtpSettings.Password);

            await smtp.SendAsync(email);

            await smtp.DisconnectAsync(true);
        }
        public async Task <string> GetConfirmAccountTemplateAsync(string confirmationLink)
        {
            var    viewModel = new ConfirmAccountViewModel(confirmationLink);
            string viewName  = "/Views/Emails/ConfirmAccount/ConfirmAccount.cshtml";
            var    result    = await razorViewToStringRenderer.RenderViewToStringAsync(viewName, viewModel);

            return(result);
        }
示例#3
0
        public async Task Handle(RequestApprovedNotification notification, CancellationToken cancellationToken)
        {
            Request request = notification.Request;

            RequestDataForEmail model = new RequestDataForEmail
            {
                AuthorFullName = $"{request.User.FirstName} {request.User.LastName}".Trim(),
                RequestType    = request.Type.ToString(),
                StartDate      = request.StartDate.Date.ToString("dd/MM/yyyy"),
                EndDate        = request.EndDate.Date.ToString("dd/MM/yyyy"),
                Comment        = request.Comment,
                Duration       = request.EndDate.Date.Subtract(request.StartDate.Date).Days + 1,
            };


            User author = await _userManager.FindByIdAsync(request.UserId.ToString());

            model.AuthorFullName = $"{author.FirstName} {author.LastName}".Trim();

            IEnumerable <Review> reviews = await _reviewRepository.FilterAsync(rev => rev.RequestId == request.Id);

            foreach (var review in reviews)
            {
                review.Reviewer = await _userManager.FindByIdAsync(review.ReviewerId.ToString());
            }

            var approvedPeopleNames = reviews.Select(r => $"{r.Reviewer.FirstName} {r.Reviewer.LastName}".Trim()).ToList();

            model.ApprovedFullNames = string.Join(", ", approvedPeopleNames);

            var dataForViewModel = new RequestEmailViewModel(model);
            {   //Author mail
                string authorAddress = author.Email;
                string authorTheme   = string.Format(
                    model.StartDate,
                    model.EndDate);

                string authorBody = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/RequestApprove/RequestApproveForAuthor.cshtml", dataForViewModel);

                await _mailer.SendEmailAsync(authorAddress, authorTheme, authorBody);
            }

            {   //Accountant mail
                string accountantAddress = reviews.FirstOrDefault().Reviewer.Email;
                string accountantTheme   = string.Format(
                    model.AuthorFullName,
                    model.StartDate,
                    model.EndDate);

                string accountantBody = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/RequestApprove/RequestApprove.cshtml", dataForViewModel);

                await _mailer.SendEmailAsync(accountantAddress, accountantTheme, accountantBody);
            }
        }
示例#4
0
        public async Task SendConfirmEmail(string email, string baseUrl)
        {
            var confirmAccountModel = new ConfirmAccountEmailViewModel($"{baseUrl}");

            string body = await razorViewToStringRenderer
                          .RenderViewToStringAsync(
                "~/Views/Emails/ConfirmAccount/ConfirmAccountEmail.cshtml",
                confirmAccountModel);

            SendEmailAsync(email, "Confirm your Account", body);
        }
示例#5
0
        public async Task <IActionResult> ConfirmAccountEmailHtml()
        {
            var confirmAccountEmailViewModel = new ConfirmAccountEmailViewModel(true, "https://www.google.com");
            var content = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/Html/Account/ConfirmEmail.cshtml", confirmAccountEmailViewModel);

            return(new ContentResult
            {
                ContentType = "text/html",
                StatusCode = (int)HttpStatusCode.OK,
                Content = content
            });
        }
示例#6
0
        public async Task <byte[]> GetByteArray <T>(string View, T model)
        {
            try
            {
                var html = await _engine.RenderViewToStringAsync(View, model);

                return(await GetPDF(html));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#7
0
        public async Task SendBusNotification(BusMonitoring busMonitoring, string email)
        {
            var to   = new MailAddress(email);
            var body = await renderer.RenderViewToStringAsync("Templates/BusNotificationTemplate.cshtml", busMonitoring);

            var message = new MailMessage(from, to)
            {
                Subject    = $"{busMonitoring.From} - {busMonitoring.To}. Поїздки знайдено!",
                Body       = body,
                IsBodyHtml = true
            };

            SendEmail(message);
        }
示例#8
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }

                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page("/Account/ResetPassword",
                                           pageHandler: null,
                                           values: new { area = "Identity", code },
                                           protocol: Request.Scheme);

                var    emailCallback = new EmailCallbackViewModel(callbackUrl);
                string body          = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/ForgotPasswordEmail.cshtml", emailCallback);

                await _emailSender.SendEmailAsync(Input.Email, "mtgdm - Reset password", body);

                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(Page());
        }
示例#9
0
        private async Task <EmailProtoType> CreateEmail(int companyid, CompanyUser user, MassEmail em)
        {
            EmailProtoType res = new EmailProtoType();

            try
            {
                var model = await CreateEmailModel(companyid, user, em);

                res.JustAttachment = model.JustAttachment;
                if (!res.JustAttachment)
                {
                    string viewname = $"/Views/MassEmail/{em.TemplateName}_Template.cshtml";
                    res.Message = await _razorViewToStringRenderer.RenderViewToStringAsync(viewname, model);
                }
                model.Attachments.ForEach(a => res.Attachments.Add(a));
                if (string.IsNullOrEmpty(model.Subject))
                {
                    res.Subject = string.IsNullOrEmpty(em.Subject) ? "Info" : em.Subject;
                }
                else
                {
                    res.Subject = model.Subject;
                }
                // var user = _userManager.Users.SingleOrDefault(u => u.Id == userid);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "CreateEmail error");
                return(null);
            }
            return(res);
        }
示例#10
0
        public async Task <IActionResult> PostSendInvoiceEmail([FromBody] InvoiceEmailRequestModel invoice)
        {
            var result = new ResultModel();

            var invoiceModel = _invoiceService.SearchInvoice(invoice.InvoiceId);

            if (invoiceModel != null)
            {
                try
                {
                    string body = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/Invoices/Invoice.cshtml", invoiceModel);

                    await _emailSender.SendEmailAsync(invoiceModel.PatientEmail, "SMLYS invoice", string.Empty, body);

                    result.Success = true;
                    result.Message = "Email has been sent successfully.";
                }
                catch (Exception ex)
                {
                    result.Message = "Oops, Email was not sent. please try again. ";
                }
            }
            else
            {
                result.Message = "Invalid invoice Id, Please choose right one and try again. ";
            }

            return(Json(result));
        }
示例#11
0
        //public string GetSmtpAdress()
        //{
        //    return _emailConfiguration.SmtpServer;
        //}
        public async Task <bool> SendEmailFromTemplate <TModel>(int comapnyid, string subject, string email, string templateName, TModel model)
        {
            try
            {
                string viewname = $"/Views/MassEmail/{templateName}_Template.cshtml";
                string body     = await _razorViewToStringRenderer.RenderViewToStringAsync(viewname, model);
                await SendEmailAsync(email, subject, body, comapnyid);

                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "SendEmailFromTemplate");
                return(false);
            }
        }
        public async Task Handle(OrderCompletedDomainEvent domainEvent, CancellationToken cancellationToken)
        {
            var model = _mapper.Map <OrderModel>(domainEvent.Order);
            var view  = await _razorView.RenderViewToStringAsync(Path.Combine("Views", "Orders", "OrderCompletedView.cshtml"), model);

            await _emailFactory.Create()
            .To(domainEvent.Order.BuyerEmail, domainEvent.Order.BuyerName)
            .Subject("Order completed")
            .Body(view, isHtml: true)
            .SendAsync();
        }
示例#13
0
        public async Task <IActionResult> ResendActivationLink(string userID, string email)
        {
            const string view           = "/Views/ActivateAccount/Index.cshtml";
            var          ActivationLink = WordPressPasswordUtil.GetActivationLink(Convert.ToString(userID), email);
            var          template       = await _renderer.RenderViewToStringAsync <Models.ActivateAccountViewModel>(view, new Models.ActivateAccountViewModel()
            {
                URL = ActivationLink
            });;

            return(Ok(await accountService.ResendActivationLink(userID, email, template)));
        }
        public async Task <bool> SendAccountVerificationEmailAsync(AppUser user, string token)
        {
            if (user == null)
            {
                return(false);
            }

            var host             = "http://zhinindas.alchemy.shop.axmouth.dev/";
            var verificationLink = $"{host}verify-email?email_confirm_token={Uri.EscapeDataString(token)}&user_name={user.UserName}";
            var model            = new AccountVerificationViewModel(verificationLink, user.UserName);
            var name             = "AccountVerification";
            var htmlBody         = await _renderer.RenderViewToStringAsync($"{templateBaseDir}/{name}/{name}Html.cshtml", model);

            var textBody = await _renderer.RenderViewToStringAsync($"{templateBaseDir}/{name}/{name}Text.cshtml", model);

            var result = await SendEmailAsync(new List <string> {
                user.Email
            }, _fromAddress, "Verify your Account's Email", textBody, htmlBody);

            return(result);
        }
示例#15
0
        public async Task <IActionResult> RegistrationAsync(RegistrationViewModel model)
        {
            model = model ?? throw new ArgumentNullException(nameof(model));

            if (ModelState.IsValid)
            {
                var(result, userId, code) = await _identityService.CreateUserAsync(model.Email, model.UserName, model.Password);

                if (result == null)
                {
                    ModelState.AddModelError(string.Empty, ErrorConstants.RegistrationEmailExist);

                    return(View(model));
                }

                if (result.Succeeded)
                {
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId, code }, protocol: HttpContext.Request.Scheme);

                    var emailModel = new EmailDTO
                    {
                        UserName = model.UserName,
                        Code     = callbackUrl
                    };

                    var body = await _razorViewToStringRenderer.RenderViewToStringAsync("Views/Email/EmailConfirm.cshtml", emailModel);

                    await _messageSender.SendMessageAsync(model.Email, ErrorConstants.AccountConfirm, body);

                    return(View("RegistartionSucceeded"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error);
                }
            }

            return(View(model));
        }
示例#16
0
        public async Task PrepareDailyReport(DailyReportEmailDto dailyReportEmailDto)
        {
            if (dailyReportEmailDto.AdminEmails != null)
            {
                foreach (var item in dailyReportEmailDto.AdminEmails)
                {
                    var modelItem = new DailyReportViewModel
                    {
                        FullName       = item.FullName,
                        InactiveDomain = dailyReportEmailDto.InactiveDomain,
                        ActiveDomain   = dailyReportEmailDto.ActiveDomain,
                        AdsNotEqual    = dailyReportEmailDto.AdsNotEqual,
                        AdsNotFound    = dailyReportEmailDto.AdsNotFound,
                        AdsItemError   = dailyReportEmailDto.AdsItemError,
                        LogDate        = dailyReportEmailDto.LogDate
                    };
                    var body = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/Ads/DailyReport.cshtml", modelItem);

                    await AddNotification(body, new EmailConf(item, dailyReportEmailDto.Priority), _settings.Value.DailyReport);
                }
            }
        }
        public async Task Invoke(HttpContext httpContext, ILicenseService lisenceService, IRazorViewToStringRenderer razorViewToString)
        {
            if (!lisenceService.IsValidLicense())
            {
                httpContext.Response.StatusCode = 400;
                var viewString = await razorViewToString.RenderViewToStringAsync("/Areas/Admin/Views/License/InvalidLicense.cshtml", new { });

                await httpContext.Response.WriteAsync(viewString);

                return;
            }
            await _next.Invoke(httpContext);
        }
        public async Task <IActionResult> Send()
        {
            try
            {
                var from = new MailAddress("*****@*****.**", "Derek Arends");
                var to   = new MailAddress("*****@*****.**");

                var model = new HelloWorldViewModel("https://www.google.com");

                const string view     = "/Views/Emails/HelloWorld/HelloWorld";
                var          htmlBody = await _renderer.RenderViewToStringAsync($"{view}Html.cshtml", model);

                var textBody = await _renderer.RenderViewToStringAsync($"{view}Text.cshtml", model);

                var message = new MailMessage(from, to)
                {
                    Subject = "Hello World!",
                    Body    = textBody
                };

                message.AlternateViews.Add(
                    AlternateView.CreateAlternateViewFromString(htmlBody, Encoding.UTF8, MediaTypeNames.Text.Html));

                using (var smtp = new SmtpClient("smtp.mailserver.com", 587))
                {
                    smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    smtp.UseDefaultCredentials = false;
                    smtp.EnableSsl             = true;
                    smtp.Credentials           = new NetworkCredential("smtp_user", "smtp_password");
                    await smtp.SendMailAsync(message);
                }
            }
            catch (Exception e)
            {
                return(StatusCode(500, $"Failed to send email: {e.Message}"));
            }

            return(Ok("Email Sent!"));
        }
示例#19
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.DisplayName, 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);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));

                    returnUrl = Url.Page("/Showpiece/List", pageHandler: null, values: null, protocol: Request.Scheme);
                    var callbackUrl = Url.Page("/Account/ConfirmEmail",
                                               pageHandler: null,
                                               values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                                               protocol: Request.Scheme);

                    var    confirmAccountModel = new EmailCallbackViewModel(callbackUrl);
                    string body = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/ConfirmAccountEmail.cshtml", confirmAccountModel);

                    await _emailSender.SendEmailAsync(Input.Email, "mtgdm - Complete registration", body);

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        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());
        }
        public async Task Register(string email, string baseUrl)
        {
            // TODO: Validation + actually add the User to a DB + whatever else
            // TODO: Base URL off of ASP.NET Core Identity's logic or some other mechanism, rather than hardcoding to creating a random guid
            var confirmAccountModel = new ConfirmAccountEmailViewModel($"{baseUrl}/{Guid.NewGuid()}");

            string body = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/ConfirmAccount/ConfirmAccountEmail.cshtml", confirmAccountModel);

            var toAddresses = new List <string> {
                email
            };

            SendEmail(toAddresses, "*****@*****.**", "Confirm your Account", body);
        }
示例#21
0
        public async Task SendViewBasedEmail <T>(List <EmailAddress> toAdresses, string subject, string viewName, T messageBody)
        {
            string body = await _razorViewToStringRenderer.RenderViewToStringAsync(viewName, messageBody);

            var emailMessage = new EmailMessage
            {
                Content       = body,
                Subject       = subject,
                FromAddresses = new List <EmailAddress> {
                    new EmailAddress(_emailOptions.SenderName, _emailOptions.SenderEmail)
                },
                ToAddresses = toAdresses
            };

            await Send(emailMessage);
        }
        public async Task <bool> GenerateNewsLetter()
        {
            try
            {
                var initiativeYear = await _unitOfWork.InitiativeYear.GetInitiativeYearByYear(DateTime.Now.Year);

                var initiativeList = await _unitOfWork.Initiative.GetInitiatives(initiativeYear.Id.ToString());

                var reportList = new List <NewsLetterDto>();
                foreach (var initiative in initiativeList)
                {
                    var report       = new NewsLetterDto();
                    var initiativeId = initiative.Id.ToString();
                    report.InitativeId = initiativeId;
                    report.Initative   = initiative.Name;
                    var topContributors = await _unitOfWork.InitiativeMember.GetTopContributors(initiativeId);

                    if (topContributors != null)
                    {
                        report.TopContributors = topContributors;
                    }

                    var upComingReviewCycles = await _unitOfWork.ReviewCycle.GetUpComingReviewCycles(initiativeId);

                    if (upComingReviewCycles != null)
                    {
                        report.UpComingReviewCycles = upComingReviewCycles;
                    }
                    reportList.Add(report);
                }

                var model = new NewsLetterViewModel(reportList);

                const string view     = "/Views/Emails/NewsLetter/NewsLetter";
                var          htmlBody = await _renderer.RenderViewToStringAsync($"{view}Html.cshtml", model);

                await _azureBusService.SendNewsLetterAsync(htmlBody);

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine($"error message: {e}");
                return(false);
            }
        }
示例#23
0
        public async Task Handle(RequestUpdatedNotification notification, CancellationToken cancellationToken)
        {
            Request request = notification.Request;

            RequestDataForEmail model = new RequestDataForEmail
            {
                AuthorFullName = $"{request.User.FirstName} {request.User.LastName}".Trim(),
                RequestType    = request.Type.ToString(),
                StartDate      = request.StartDate.Date.ToString("dd/MM/yyyy"),
                EndDate        = request.EndDate.Date.ToString("dd/MM/yyyy"),
                Comment        = request.Comment,
                Duration       = request.EndDate.Date.Subtract(request.StartDate.Date).Days + 1,
            };

            User author = await _userManager.FindByIdAsync(request.UserId.ToString());

            model.AuthorFullName = $"{author.FirstName} {author.LastName}".Trim();

            IEnumerable <Review> reviews = await _reviewRepository.FilterAsync(rev => rev.RequestId == request.Id);

            foreach (var review in reviews)
            {
                review.Reviewer = await _userManager.FindByIdAsync(review.ReviewerId.ToString());
            }

            var approvedPeopleNames = reviews.Where(r => r.IsApproved == true).Select(r => $"{r.Reviewer.FirstName} {r.Reviewer.LastName}".Trim()).ToList();

            model.ApprovedFullNames = string.Join(", ", approvedPeopleNames);

            var    curReview = reviews.Where(r => r.IsApproved == null).FirstOrDefault();
            string address   = curReview.Reviewer.Email;
            string theme     = string.Format(
                model.AuthorFullName,
                model.StartDate,
                model.EndDate
                );

            string reference = _uiConfig.Url + $"/reviews";

            var dataForViewModel = new RequestEmailViewModel(model, reference);

            string body = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/RequestUpdate/RequestUpdate.cshtml", dataForViewModel);

            await _mailer.SendEmailAsync(address, theme, body);
        }
示例#24
0
        public async Task UserRegistered(string username, string email, string password, string token)
        {
            var emailView = new ConfirmMailboxEmailViewModel
            {
                Token    = token,
                Username = username,
                Password = password
            };

            var message = new MailMessage
            {
                BodyHtml = await _razorViewToStringRenderer.RenderViewToStringAsync("ConfirmMailboxEmailView", emailView),
                From     = "*****@*****.**",
                To       = email,
                Subject  = "Thank you for your registration"
            };
            await _mailSenderService.SendEmailAsync(message);
        }
示例#25
0
        public async Task SendMentorInviteEmail(Mentor mentor, string token)
        {
            var mentorInviteEmailModel = new MentorInviteEmailModel
            {
                FirstName       = mentor.FirstName,
                LastName        = mentor.LastName,
                IconUrl         = _webHostService.GetWebIconUrl(),
                RegistrationUrl = _webHostService.GetRegistrationUrl(token)
            };

            var body = await _razorViewToStringRenderer.RenderViewToStringAsync(Templates.MentorInviteView,
                                                                                mentorInviteEmailModel);

            await _emailSenderService.SendEmail(new EmailMessage(new List <string> {
                mentor.Email
            },
                                                                 "Student mentor registration", body));
        }
示例#26
0
        private async Task SendEmailAsync <TModel>(string email, string subject, TModel model, string templateName = DefaultTemplate)
            where TModel : EmailModel
        {
            try
            {
                var mimeMessage = new MimeMessage();

                mimeMessage.From.Add(new MailboxAddress(_emailSettings.SenderName, _emailSettings.Sender));
                mimeMessage.To.Add(MailboxAddress.Parse(email));
                mimeMessage.Subject = subject;

                mimeMessage.Body = new TextPart("html")
                {
                    Text = await _razor.RenderViewToStringAsync(templateName, model)
                };

                using var client = new SmtpClient
                      {
                          ServerCertificateValidationCallback = (s, c, h, e) => true
                      };

                if (_env.IsDevelopment())
                {
                    // The third parameter is useSSL (true if the client should make an SSL-wrapped
                    // connection to the server; otherwise, false).
                    await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, true);
                }
                else
                {
                    await client.ConnectAsync(_emailSettings.MailServer);
                }

                // Note: only needed if the SMTP server requires authentication
                await client.AuthenticateAsync(_emailSettings.Sender, _emailSettings.Password);

                await client.SendAsync(mimeMessage);

                await client.DisconnectAsync(true);
            }
            catch (Exception e)
            {
                Log.LogError(e, "Error while sending email: {0}", e.Message);
            }
        }
示例#27
0
        public async Task <IActionResult> OnPostChangeEmailAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(new RedirectResult("/Identity/Account/Login"));
            }

            if (!ModelState.IsValid)
            {
                await LoadAsync(user);

                return(Page());
            }

            var email = await _userManager.GetEmailAsync(user);

            if (Input.NewEmail != email)
            {
                var userId = await _userManager.GetUserIdAsync(user);

                var code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail);

                var callbackUrl = Url.Page("/Account/ConfirmEmailChange",
                                           pageHandler: null,
                                           values: new { userId = userId, email = Input.NewEmail, code = code },
                                           protocol: Request.Scheme);

                var    emailCallback = new EmailCallbackViewModel(callbackUrl);
                string body          = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Emails/EmailChangeEmail.cshtml", emailCallback);

                await _emailSender.SendEmailAsync(Input.NewEmail, "mtgdm - Confirm your email", body);

                ChangeEmailStatusMessage = "Check your email for a link to change your email address. If it doesn’t appear within a few minutes, check your spam folder.";
                return(RedirectToPage());
            }
            Email = email;
            ModelState.AddModelError("Validation.SameEmail", "Email addresses are the same");
            return(Page());
        }
示例#28
0
        public async Task <IActionResult> SendInvoice(int orderId)
        {
            var order                 = orderService.GetOrderById(orderId);
            var client                = clientService.GetClientById(order.IdClient);
            var infos                 = deliveryInfoService.GetOrderDeliveryInfo(orderId);
            var orderProducts         = productOrderService.GetOrderProducts(order);
            var signatureBase64String = Convert.ToBase64String(infos.SignatureImageBase64);


            var dto = new List <OrderProductDto>();

            foreach (var prod in orderProducts)
            {
                var product = productService.GetProductById(prod.IdProduct);
                dto.Add(new OrderProductDto
                {
                    Product      = product,
                    ProductImage = productImageService.GetProductImages(product).FirstOrDefault(),
                    OrderProduct = prod
                });
            }

            var invoiceViewModel = new InvoiceDto
            {
                Order                 = order,
                DeliveryInfo          = infos,
                Client                = client,
                OrderProducts         = dto,
                SignatureBase64String = signatureBase64String
            };

            string body = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Order/Invoice.cshtml", invoiceViewModel);

            await emailSenderService.SendEmail(client.Email, "Facture", body);

            order.WithBill = false;
            orderService.EditOrder(order);

            TempData["Message"] = "Facture envoyée à " + client.FirstName + " " + client.LastName;
            return(RedirectToAction("DeliveredOrders"));
        }
示例#29
0
        public async Task <IActionResult> SubmissionConfirmaitionEmail(long id, [FromServices] IRazorViewToStringRenderer _razorViewToStringRenderer, [FromServices] IEmailSender _emailSender, [FromServices] IFileService fileService)
        {
            var model     = HttpContext.RequestServices.GetService <ISubmissionService>().GetAuthorSubmissionViewModel(id, (((JMSPrincipal)User).ApplicationUser.Id), TenantID);
            var emailBody = await _razorViewToStringRenderer.RenderViewToStringAsync(@"/Views/Submission/SubmissionConfirmaitionEmail.cshtml", model);

            var mailMessage = new MailMessage(_configuration[JMSSetting.SenderEmail], ((JMSPrincipal)User).ApplicationUser.Email, _configuration[JMSSetting.SubmissionConfirmationSubject], emailBody)
            {
                IsBodyHtml = true
            };

            foreach (var file in model.Files)
            {
                mailMessage.Attachments.Add(new Attachment(new MemoryStream(fileService.GetFileBytes(file.FileId)), file.FileName));
            }
            model.Contributers.ForEach(x =>
            {
                mailMessage.CC.Add(x.Email);
            });
            _emailSender.SendEmail(mailMessage);
            return(Ok());
        }
        public async Task <IActionResult> TestSendMail()
        {
            string body = string.Empty;
            //string path = Path.Combine(Environment.CurrentDirectory, "\\Project\\bkc-backend\\bkc-backend.Api\\Views\\EmailTemplate\\EmailNoti.cshtml");
            string path = "/Views/Share/EmailNotify.cshtml";

            //using (StreamReader reader = new StreamReader(path))
            //{
            //    body = reader.ReadToEnd();
            //}
            body = await _razorViewToStringRenderer.RenderViewToStringAsync(path, new TemModel());

            var mailContent = new MailContent();

            mailContent.To      = "*****@*****.**";
            mailContent.Subject = "Test Email";
            mailContent.Body    = body;
            await _sendMailServices.SendMail(mailContent);

            return(Ok());
        }