public async Task <HttpResponseMessage> CreateNotifications(NotificationDTO notify)
        {
            HttpResponseMessage responce;

            try
            {
                notify = await _notificationDataService.CreateNotification(notify);

                _logger.Info($"SendMailController.SendMail [notification.Id: {notify.Id} notification.Protocol: {notify.Protocol}]");

                if (Enum.IsDefined(typeof(Protocol), notify.Protocol))
                {
                    switch ((Protocol)Enum.Parse(typeof(Protocol), notify.Protocol, true))
                    {
                    case Protocol.Email:
                        await _smtpService.SendAsync(notify.Receiver, notify.Body, notify.Channel);

                        break;

                    case Protocol.SignalR:
                        await NotificationsHub.SendNotification(notify.Receiver, notify);

                        break;
                    }
                }
                responce = Request.CreateResponse(HttpStatusCode.OK, notify);
            }
            catch (Exception ex)
            {
                _logger.Error($"SendMailController.SendMail [mail.Id: {notify.Id}]", ex);
                responce = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return(responce);
        }
Пример #2
0
        public async Task <IActionResult> SendEmail(SendEmailTemplateViewModel model, string returnUrl)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageEmailTemplates))
            {
                return(Forbid());
            }

            if (ModelState.IsValid)
            {
                var message = _emailTemplatesService.CreateMessageFromViewModel(model);

                var result = await _smtpService.SendAsync(message);

                if (!result.Succeeded)
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("*", error.ToString());
                    }
                }
                else
                {
                    _notifier.Success(H["Message sent successfully"]);
                    return(Redirect(returnUrl));
                }
            }

            return(View(model));
        }
        protected async Task <bool> SendEmailAsync(string email, string subject, IShape model)
        {
            var body = string.Empty;

            using (var sb = StringBuilderPool.GetInstance())
            {
                using (var sw = new StringWriter(sb.Builder))
                {
                    var htmlContent = await _displayHelper.ShapeExecuteAsync(model);

                    htmlContent.WriteTo(sw, HtmlEncoder.Default);
                    body = sw.ToString();
                }
            }

            var message = new MailMessage()
            {
                To         = email,
                Subject    = subject,
                Body       = body,
                IsBodyHtml = true
            };

            var result = await _smtpService.SendAsync(message);

            return(result.Succeeded);
        }
Пример #4
0
        protected override async ValueTask <IActivityExecutionResult> OnExecuteAsync(ActivityExecutionContext context)
        {
            var cancellationToken = context.CancellationToken;
            var message           = new MimeMessage();
            var from = string.IsNullOrWhiteSpace(From) ? _options.DefaultSender : From;

            message.Sender  = MailboxAddress.Parse(from);
            message.Subject = Subject;

            var bodyBuilder = new BodyBuilder {
                HtmlBody = Body
            };

            await AddAttachmentsAsync(bodyBuilder, cancellationToken);

            message.Body = bodyBuilder.ToMessageBody();

            SetRecipientsEmailAddresses(message.To, To);
            SetRecipientsEmailAddresses(message.Cc, Cc);
            SetRecipientsEmailAddresses(message.Bcc, Bcc);

            await _smtpService.SendAsync(context, message, context.CancellationToken);

            return(Done());
        }
Пример #5
0
        async Task IGangEventHandler <GangManagerEvent <GangUserLink> > .HandleAsync(
            GangManagerEvent <GangUserLink> e)
        {
            var message = new MailMessage
            {
                Subject = "Gang Demo: Invite"
            };

            message.To.Add(new MailAddress(e.Data.Email, e.Data.Name));

            var uri = QueryHelpers.AddQueryString(
                _app.RootUrl + "/", new Dictionary <string, string> {
                { "link-code", e.Data.Code.Value }
            });

            message.Body =
                $@"Hi {e.Data.Name},

An invite to the Gang Demo was requested for {e.Data.Email}

{e.Data.Code.Value}

enter the code or click the link below to gain access
{uri}";

            await _smtp.SendAsync(message);
        }
Пример #6
0
        public async Task <IActionResult> Post(SmtpSettingsViewModel model)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageEmailSettings))
            {
                return(Unauthorized());
            }

            if (ModelState.IsValid)
            {
                var message = CreateMessageFromViewModel(model);

                // send email with DefaultSender
                var result = await _smtpService.SendAsync(message);

                if (!result.Succeeded)
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("*", error.ToString());
                    }
                }
                else
                {
                    _notifier.Success(H["Message sent successfully"]);

                    return(Redirect(Url.Action("Index", "Admin", new { area = "OrchardCore.Settings", groupId = SmtpSettingsDisplayDriver.GroupId })));
                }
            }

            return(View(model));
        }
Пример #7
0
        public async Task SendAsync(OperationContext context, NotificationMessage message)
        {
            Util.CheckNotEmpty(message.Recipients, "Recipient(s) not specified.");
            try {
                var session = context.OpenSystemSession();
                var subject = message.GetString("Subject") ?? GetTemplatedValue(session, message, "Subject");
                var body    = message.GetString("Body") ?? GetTemplatedValue(session, message, "Body");
                Util.CheckNotEmpty(message.From, "Email From address not specified in message.");
                Util.CheckNotEmpty(subject, "Subject not specified or Subject template '{0}.Subject' not found.", message.Type);
                Util.CheckNotEmpty(body, "Email body not specified or Body template '{0}.Body' not found.", message.Type);
                message.Body = body;
                if (message.Status == MessageStatus.Blocked)
                {
                    return;
                }
                message.Status = MessageStatus.Sending;
                var mail = new MailMessage(message.From, message.Recipients, subject, body);
                await _smtpService.SendAsync(context, mail);

                message.Status = MessageStatus.Sent;
            } catch (Exception ex) {
                message.Status = MessageStatus.Error;
                message.Error  = ex.ToLogString();
            }
        }
Пример #8
0
        protected async Task <bool> SendEmailAsync(string email, string subject, object model, string viewName)
        {
            var options = ControllerContext.HttpContext.RequestServices.GetRequiredService <IOptions <MvcViewOptions> >();

            ControllerContext.RouteData.Values["action"]     = viewName;
            ControllerContext.RouteData.Values["controller"] = "";
            var viewEngineResult = options.Value.ViewEngines.Select(x => x.FindView(ControllerContext, viewName, true)).FirstOrDefault(x => x != null);
            var displayContext   = new DisplayContext()
            {
                ServiceProvider = ControllerContext.HttpContext.RequestServices,
                Value           = await _shapeFactory.CreateAsync(viewName, model),
                ViewContext     = new ViewContext(ControllerContext, viewEngineResult.View, ViewData, TempData, new StringWriter(), new HtmlHelperOptions())
            };
            var htmlContent = await _displayManager.ExecuteAsync(displayContext);

            var message = new MailMessage()
            {
                Body = WebUtility.HtmlDecode(htmlContent.ToString()), IsBodyHtml = true, Subject = subject
            };

            message.To.Add(email);

            // send email
            var result = await _smtpService.SendAsync(message);

            return(result.Succeeded);
        }
Пример #9
0
        public async Task SendEmailAsync(IEmail email)
        {
            var campaignSettings = await _campaignSettingsRepository.GetCachedAsync(email.CampaignId,
                                                                                    reloadIf : x => x?.Smtp == null);

            await _smtpService.SendAsync(email, campaignSettings.Smtp);

            await _emailRepository.InsertAsync(email);

            await _log.WriteInfoAsync(nameof(SendEmailAsync),
                                      $"Campaign: {email.CampaignId}, Template: {email.TemplateId}, To: {email.To}",
                                      $"Email sent to {email.To}");
        }
Пример #10
0
    /*==========================================================================================================================
    | HELPER: SEND INTERNAL RECEIPT (ASYNC)
    \-------------------------------------------------------------------------------------------------------------------------*/
    /// <summary>
    ///   Send an email to GoldSim containing all of the form values.
    /// </summary>
    private async Task SendInternalReceipt(string subject = null, string recipient = null, string sender = null) {

      /*------------------------------------------------------------------------------------------------------------------------
      | Establish variables
      \-----------------------------------------------------------------------------------------------------------------------*/
      subject                   ??= "GoldSim.com/Forms: " + CurrentTopic.Key;
      recipient                 ??= "*****@*****.**";
      sender                    ??= "*****@*****.**";

      /*------------------------------------------------------------------------------------------------------------------------
      | Assemble email
      \-----------------------------------------------------------------------------------------------------------------------*/
      var mail                  = new MailMessage(new MailAddress(sender), new MailAddress(recipient)) {
        Subject                 = subject,
        Body                    = GetEmailBody(),
        IsBodyHtml              = true
      };

      /*------------------------------------------------------------------------------------------------------------------------
      | Send email
      \-----------------------------------------------------------------------------------------------------------------------*/
      await _smptService.SendAsync(mail);

    }
        public Task Handle(DeploymentFinishedNotification notification, CancellationToken cancellationToken)
        {
            if (!_emailNotificationConfiguration.Enabled)
            {
                return(Task.CompletedTask);
            }

            if (!_emailNotificationConfiguration.IsValid)
            {
                return(Task.CompletedTask);
            }

            string result = notification.DeploymentTask.Status == WorkTaskStatus.Done ? "succeeded" : "failed";

            string subject =
                $"Deployment of {notification.DeploymentTask.PackageId} {notification.DeploymentTask.SemanticVersion.ToNormalizedString()} to {notification.DeploymentTask.DeploymentTargetId} {result}";

            string body = $@"{notification.DeploymentTask.DeploymentTargetId}
Status: {notification.DeploymentTask.Status}
Finished at time (UTC): {notification.FinishedAtUtc:O}
Package ID: {notification.DeploymentTask.PackageId}
Deployment task ID: {notification.DeploymentTask.DeploymentTaskId}
Version: {notification.DeploymentTask.SemanticVersion.ToNormalizedString()}
Log: {notification.Log}
";

            var message = new MimeMessage
            {
                Body = new TextPart("plain")
                {
                    Text = body
                },
                Subject = subject
            };

            foreach (Email email in _emailNotificationConfiguration.To)
            {
                message.To.Add(new MailboxAddress(email.Address));
            }

            if (_emailNotificationConfiguration.From != null)
            {
                message.From.Add(new MailboxAddress(_emailNotificationConfiguration.From.Address));
            }

            return(_smtpService.SendAsync(message, cancellationToken));
        }
Пример #12
0
        public async Task <IActionResult> IndexPost(RegisterUserViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var shellSettings = new ShellSettings
                {
                    Name             = viewModel.Handle,
                    RequestUrlPrefix = viewModel.Handle,
                    RequestUrlHost   = "",
                    // this should be a setting in the SaaS module
                    ["ConnectionString"] = "", //ComponentChangedEventArgs by giannis
                    //  ConnectionString = "",
                    //TablePrefix = "",
                    ["TablePrefix"] = "",
                    //  DatabaseProvider = "Sqlite",
                    ["DatabaseProvider"] = "Sqlite",
                    State = TenantState.Uninitialized,
                    // Secret = Guid.NewGuid().ToString(),
                    //RecipeName = "Blog"
                };


                await _shellSettingsManager.SaveSettingsAsync(shellSettings);

                var shellContext = await _shellHost.GetOrCreateShellContextAsync(shellSettings);

                var confirmationLink = Url.Action("Confirm", "Home",
                                                  new { email = viewModel.Email, handle = viewModel.Handle, siteName = viewModel.SiteName },
                                                  Request.Scheme);

                var message = new OrchardCore.Email.MailMessage();
                message.From       = "*****@*****.**"; // new MailAddress("*****@*****.**", "Orchard SaaS");
                message.To         = viewModel.Email;     ////.Add(viewModel.Email);
                message.IsBodyHtml = true;
                message.Body       = $"Click <a href=\"{HttpUtility.HtmlEncode(confirmationLink)}\">this link</a>";
                ;


                await _smtpService.SendAsync(message);

                return(RedirectToAction(nameof(Success)));
            }

            return(View("Index", viewModel));
        }
Пример #13
0
        public async Task <IActionResult> SendMail([FromBody] Notification.Model.Notification notification)
        {
            if (notification == null)
            {
                return(BadRequest());
            }

            notification.Id = Guid.NewGuid().ToString();

            await Task.Run(() =>
            {
                _context.Notifications.AddAsync(notification);
                _context.SaveChanges();
            });

            await _smtpService.SendAsync(notification.Receiver, notification.Body, notification.Title);

            return(Ok());
        }
Пример #14
0
        protected async Task <bool> SendEmailAsync(string email, string subject, IShape model)
        {
            var options = ControllerContext.HttpContext.RequestServices.GetRequiredService <IOptions <MvcViewOptions> >();

            // Just use the current context to get a view and then create a view context.
            var view = options.Value.ViewEngines
                       .Select(x => x.FindView(
                                   ControllerContext,
                                   ControllerContext.ActionDescriptor.ActionName,
                                   false)).FirstOrDefault()?.View;

            var displayContext = new DisplayContext()
            {
                ServiceProvider = ControllerContext.HttpContext.RequestServices,
                Value           = model,
                ViewContext     = new ViewContext(ControllerContext, view, ViewData, TempData, new StringWriter(), new HtmlHelperOptions())
            };

            var body = string.Empty;

            using (var sw = new StringWriter())
            {
                var htmlContent = await _displayManager.ExecuteAsync(displayContext);

                htmlContent.WriteTo(sw, HtmlEncoder.Default);
                body = sw.ToString();
            }

            var message = new MailMessage()
            {
                Body       = body,
                IsBodyHtml = true,
                Subject    = subject
            };

            message.To.Add(email);

            var result = await _smtpService.SendAsync(message);

            return(result.Succeeded);
        }
Пример #15
0
        protected override async ValueTask <IActivityExecutionResult> OnExecuteAsync(ActivityExecutionContext context)
        {
            var message = new MimeMessage();
            var from    = From is null or "" ? _options.DefaultSender : From;

            message.From.Add(MailboxAddress.Parse(from));
            message.Subject = Subject;

            message.Body = new TextPart(TextFormat.Html)
            {
                Text = Body
            };

            SetRecipientsEmailAddresses(message.To, To);
            SetRecipientsEmailAddresses(message.Cc, Cc);
            SetRecipientsEmailAddresses(message.Bcc, Bcc);

            await _smtpService.SendAsync(message, context.CancellationToken);

            return(Done());
        }
Пример #16
0
        protected override async ValueTask <IActivityExecutionResult> OnExecuteAsync(ActivityExecutionContext context)
        {
            var cancellationToken = context.CancellationToken;
            var message           = new MimeMessage();
            var from = string.IsNullOrWhiteSpace(From) ? _options.DefaultSender : From;

            message.Sender = MailboxAddress.Parse(from);
            message.From.Add(MailboxAddress.Parse(from));
            message.Subject = Subject;

            var bodyBuilder = new BodyBuilder {
                HtmlBody = Body
            };

            await AddAttachmentsAsync(bodyBuilder, cancellationToken);

            message.Body = bodyBuilder.ToMessageBody();

            SetRecipientsEmailAddresses(message.To, To);
            SetRecipientsEmailAddresses(message.Cc, Cc);
            SetRecipientsEmailAddresses(message.Bcc, Bcc);

            var outcomes = new List <string> {
                OutcomeNames.Done
            };

            try
            {
                await _smtpService.SendAsync(context, message, context.CancellationToken);

                outcomes.Add("Success");
            }
            catch (Exception ex)
            {
                outcomes.Add("Unexpected Error");
                context.JournalData.Add("Error", ex.Message);
            }

            return(Outcomes(outcomes));
        }
        public async Task <IActionResult> IndexPost(RegisterUserViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var shellSettings = new ShellSettings
                {
                    Name             = viewModel.Handle,
                    RequestUrlPrefix = viewModel.Handle,
                    RequestUrlHost   = "",
                    // This should be a setting in the SaaS module.
                    ConnectionString = "",
                    TablePrefix      = "",
                    DatabaseProvider = "Sqlite",
                    State            = TenantState.Uninitialized,
                    Secret           = Guid.NewGuid().ToString(),
                    RecipeName       = "Blog"
                };

                _shellSettingsManager.SaveSettings(shellSettings);

                var confirmationLink = Url.Action(nameof(HomeController.Confirm), "Home", new { email = viewModel.Email, handle = viewModel.Handle, siteName = viewModel.SiteName }, Request.Scheme);

                var message = new MailMessage
                {
                    From       = new MailAddress("*****@*****.**", "Orchard SaaS"),
                    IsBodyHtml = true,
                    Body       = $"Click <a href=\"{HttpUtility.HtmlEncode(confirmationLink)}\">this link</a>"
                };

                message.To.Add(viewModel.Email);

                await _smtpService.SendAsync(message);

                return(RedirectToAction(nameof(Success)));
            }

            return(View(nameof(Index), viewModel));
        }
Пример #18
0
        public async Task <ICommandResult <MailMessage> > SendAsync(MailMessage message)
        {
            var result = new SmtpResult();

            // Ensure we've configured required email settings
            if (_smtpSettings?.DefaultFrom == null)
            {
                return(result.Failed("Email settings must be configured before an email can be sent."));
            }

            // Use application email if no from is specified
            if (message.From == null)
            {
                message.From = new MailAddress(_smtpSettings.DefaultFrom);
            }

            // Invoke EmailSending subscriptions
            foreach (var handler in _broker.Pub <MailMessage>(this, "EmailSending"))
            {
                message = await handler.Invoke(new Message <MailMessage>(message, this));
            }

            // Attempt to send the email
            var sendResult = await _smtpService.SendAsync(message);

            if (sendResult.Succeeded)
            {
                // Invoke EmailSent subscriptions
                foreach (var handler in _broker.Pub <MailMessage>(this, "EmailSent"))
                {
                    message = await handler.Invoke(new Message <MailMessage>(message, this));
                }
                return(result.Success(message));
            }

            return(result.Failed(sendResult.Errors.ToArray()));
        }
        private Task SendAuthenticationCodeByEmailAsync(User user)
        {
            //TODO: Implementar pattern para templates de e-mail na aplicação.

            var template = @"<!DOCTYPE html>
<html>
<head>
    <meta charset='utf - 8' />
    <title>{ASSUNTO_EMAIL}</title>
</head>
<body>
    <p> Seu código de acesso é: {CODIGO_ACESSO}.</p>
</body>
</html>";

            var body = template;

            var subject = "[Guadalupe.Conexão] Código de Acesso.";

            body = body.Replace("{ASSUNTO_EMAIL}", subject);
            body = body.Replace("{CODIGO_ACESSO}", user.CodeAccess);

            return(_smtpService.SendAsync(user.Person.Email, subject, body));
        }
Пример #20
0
        public async Task Handle(DeploymentMetadataLogNotification notification, CancellationToken cancellationToken)
        {
            if (!_emailConfiguration.IsValid)
            {
                _logger.Warning("Email configuration is invalid {Configuration}", _emailConfiguration);
                return;
            }

            if (!_emailConfiguration.EmailEnabled)
            {
                _logger.Debug(
                    "Email is disabled, skipping sending deployment finished email for notification {Notification}",
                    notification);
                return;
            }

            using (var cancellationTokenSource =
                       new CancellationTokenSource(TimeSpan.FromSeconds(_emailConfiguration.NotificationTimeOutInSeconds)))
            {
                DeploymentTarget target =
                    await _targetSource.GetDeploymentTargetAsync(notification.DeploymentTask.DeploymentTargetId,
                                                                 cancellationTokenSource.Token);

                if (target is null)
                {
                    return;
                }

                if (!target.EmailNotificationAddresses.Any())
                {
                    return;
                }

                var mimeMessage = new MimeMessage();

                foreach (string targetEmailNotificationAddress in target.EmailNotificationAddresses)
                {
                    try
                    {
                        mimeMessage.To.Add(new MailboxAddress(targetEmailNotificationAddress));
                    }
                    catch (Exception ex) when(!ex.IsFatal())
                    {
                        _logger.Error(ex,
                                      "Could not add email address {EmailAddress} when sending deployment finished notification email",
                                      targetEmailNotificationAddress);
                    }
                }

                mimeMessage.Body = new TextPart
                {
                    Text =
                        $@"Deployment finished for {notification.DeploymentTask}
{notification.Result.Metadata}"
                };

                mimeMessage.Subject = $"Deployment finished for {notification.DeploymentTask}";

                try
                {
                    await _smtpService.SendAsync(mimeMessage, cancellationTokenSource.Token);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    _logger.Error(ex,
                                  "Could not send email to '{To}'",
                                  string.Join(", ", target.EmailNotificationAddresses));
                }
            }
        }
Пример #21
0
 /// <summary>
 /// Sends an asynchronous mail.
 /// The 'from' value comes from the configuration file and can be overrided from options.
 /// </summary>
 ///
 /// <param name="to">
 /// To field.
 /// </param>
 ///
 /// <param name="subject">
 /// Mail subject.
 /// </param>
 ///
 /// <param name="message">
 /// Mail message.
 /// </param>
 ///
 /// <param name="options">
 /// Options (optional).
 /// </param>
 public async Task SendAsync(string to, string subject, string message, SmtpServiceOptions options = null)
 {
     await _smtpService.SendAsync(to, subject, message, options);
 }
Пример #22
0
    /*==========================================================================================================================
    | FUNCTION: SEND EMAIL RECEIPT
    \-------------------------------------------------------------------------------------------------------------------------*/
    /// <summary>
    ///   Sends an email receipt to GoldSim providing a record of the transaction.
    /// </summary>
    private async Task SendEmailReceipt(Result<Transaction> result, PaymentFormBindingModel bindingModel) {

      /*------------------------------------------------------------------------------------------------------------------------
      | Set up notification email
      \-----------------------------------------------------------------------------------------------------------------------*/
      var notificationEmail     = new MailMessage(new MailAddress("*****@*****.**"), new MailAddress("*****@*****.**"));
      var emailSubjectPrefix    = "GoldSim Payments: Credit Card Payment for Invoice";
      var emailBody             = new StringBuilder("");
      var transaction           = result.Target?? result.Transaction;
      var creditCard            = transaction?.CreditCard;

      /*------------------------------------------------------------------------------------------------------------------------
      | Apply common attributes
      \-----------------------------------------------------------------------------------------------------------------------*/
      emailBody.AppendLine();
      emailBody.AppendLine("Transaction details:");
      emailBody.AppendLine(" - Cardholder Name: "               + bindingModel.CardholderName);
      emailBody.AppendLine(" - Customer Email: "                + bindingModel.Email);
      emailBody.AppendLine(" - Company Name: "                  + bindingModel.Organization);
      emailBody.AppendLine(" - Invoice Number: "                + bindingModel.InvoiceNumber);
      emailBody.AppendLine(" - Amount: "                        + "$" + bindingModel.InvoiceAmount);
      emailBody.AppendLine(" - Credit Card (Last Four Digits): "+ creditCard?.LastFour?? "Not Available");
      emailBody.AppendLine(" - Card Type: "                     + creditCard?.CardType.ToString()?? "Not Available");

      /*------------------------------------------------------------------------------------------------------------------------
      | Process successful result
      \-----------------------------------------------------------------------------------------------------------------------*/
      if (result.IsSuccess() && transaction != null && TransactionSuccessStatuses.Contains(transaction.Status)) {
        notificationEmail.Subject = $"{emailSubjectPrefix} {bindingModel.InvoiceNumber} Successful";
        emailBody.Insert(0, "PAYMENT STATUS: " + transaction.Status.ToString().ToUpper().Replace("_", " "));
        notificationEmail.Body = emailBody.ToString();
        await _smtpService.SendAsync(notificationEmail);
        return;
      }

      /*------------------------------------------------------------------------------------------------------------------------
      | Process unsuccessful result
      \-----------------------------------------------------------------------------------------------------------------------*/
      notificationEmail.Subject = $"{emailSubjectPrefix} {bindingModel.InvoiceNumber} Failed";

      if (transaction != null) {
        var status = transaction.ProcessorResponseText;

        if (String.IsNullOrEmpty(status)) {
          status = transaction.Status.ToString();
        }

        emailBody.Insert(0, "PAYMENT STATUS: " + status.ToUpper().Replace("_", " "));
      }
      else {
        emailBody.Insert(0, "PAYMENT STATUS: NOT AVAILABLE");
      }

      /*------------------------------------------------------------------------------------------------------------------------
      | Process errors
      \-----------------------------------------------------------------------------------------------------------------------*/

      // Display general error message
      ModelState.AddModelError(
        "Transaction",
        "Your transaction was unsuccessful. Please correct any errors with your submission or contact GoldSim at " +
        "[email protected] or +1 (425)295-6985 for assistance."
      );

      // Display transaction message returned from Braintree
      if (!String.IsNullOrEmpty(result.Message)) {
        ModelState.AddModelError("Transaction", "Payment Status: " + result.Message);
        emailBody.AppendLine(" - Transaction Result: " + result.Message);
      }

      // Display any specific error messages returned from Braintree
      foreach (var error in result.Errors.DeepAll()) {
        ModelState.AddModelError(error.Code.ToString(), "Error: " + error.Message);
        emailBody.AppendLine(" - Error: " + error.Message);
      }

      /*------------------------------------------------------------------------------------------------------------------------
      | Send email
      \-----------------------------------------------------------------------------------------------------------------------*/
      notificationEmail.Body = emailBody.ToString();
      await _smtpService.SendAsync(notificationEmail);

    }
        public async Task <IActionResult> IndexPost(RegisterUserViewModel model)
        {
            if (!model.AcceptTerms)
            {
                ModelState.AddModelError(nameof(RegisterUserViewModel.AcceptTerms), S["Please, accept the terms and conditions."]);
            }

            if (!string.IsNullOrEmpty(model.Handle) && !Regex.IsMatch(model.Handle, @"^\w+$"))
            {
                ModelState.AddModelError(nameof(RegisterUserViewModel.Handle), S["Invalid tenant name. Must contain characters only and no spaces."]);
            }

            if (ModelState.IsValid)
            {
                if (_shellHost.TryGetSettings(model.Handle, out var shellSettings))
                {
                    ModelState.AddModelError(nameof(RegisterUserViewModel.Handle), S["This site name already exists."]);
                }
                else
                {
                    shellSettings = new ShellSettings
                    {
                        Name             = model.Handle,
                        RequestUrlPrefix = model.Handle.ToLower(),
                        RequestUrlHost   = null,
                        State            = TenantState.Uninitialized
                    };
                    shellSettings["RecipeName"]       = model.RecipeName;
                    shellSettings["DatabaseProvider"] = "Sqlite";

                    await _shellSettingsManager.SaveSettingsAsync(shellSettings);

                    var shellContext = await _shellHost.GetOrCreateShellContextAsync(shellSettings);

                    var recipes = await _setupService.GetSetupRecipesAsync();

                    var recipe = recipes.FirstOrDefault(x => x.Name == model.RecipeName);

                    if (recipe == null)
                    {
                        ModelState.AddModelError(nameof(RegisterUserViewModel.RecipeName), S["Invalid recipe name."]);
                    }

                    var adminName     = defaultAdminName;
                    var adminPassword = GenerateRandomPassword();
                    var siteName      = model.SiteName;
                    var siteUrl       = GetTenantUrl(shellSettings);

                    var dataProtector     = _dataProtectionProvider.CreateProtector(dataProtectionPurpose).ToTimeLimitedDataProtector();
                    var encryptedPassword = dataProtector.Protect(adminPassword, _clock.UtcNow.Add(new TimeSpan(24, 0, 0)));
                    var confirmationLink  = Url.Action(nameof(Confirm), "Home", new { email = model.Email, handle = model.Handle, siteName = model.SiteName, ep = encryptedPassword }, Request.Scheme);

                    var message = new MailMessage();
                    if (emailToBcc)
                    {
                        message.Bcc = _smtpSettingsOptions.Value.DefaultSender;
                    }
                    message.To         = model.Email;
                    message.IsBodyHtml = true;
                    message.Subject    = emailSubject;
                    message.Body       = S[$"Hello,<br><br>Your demo site '{siteName}' has been created.<br><br>1) Setup your site by opening <a href=\"{confirmationLink}\">this link</a>.<br><br>2) Log into the <a href=\"{siteUrl}/admin\">admin</a> with these credentials:<br>Username: {adminName}<br>Password: {adminPassword}"];

                    await _smtpService.SendAsync(message);

                    return(RedirectToAction(nameof(Success)));
                }
            }

            return(View(nameof(Index), model));
        }
Пример #24
0
 public async Task SendByMailAsync(string email, SmtpServiceOptions options = null)
 {
     await _smtpService.SendAsync(email, _mailTemplate.Subject, _mailTemplate.Message, options);
 }