Exemplo n.º 1
0
    public async Task <IActionResult> Contact(IFormCollection collection)
    {
        if (collection == null)
        {
            throw new ArgumentNullException(nameof(collection));
        }

        ViewBag.NavigationZone = NavigationZone.About;

        var model = new ContactModel();

        await TryUpdateModelAsync <ContactModel>(model);

        model.RecaptchaSiteKey = _captchaService.SiteKey;
        model.SubmitAttempted  = true;

        if (ModelState.IsValid)
        {
            model.IsHuman = await _captchaService.VerifyAsync(collection["g-recaptcha-response"]);

            if (!model.IsHuman)
            {
                ModelState.AddModelError("IsHuman", "The Captcha was not solved correctly, please try again");
            }
            else
            {
                try
                {
                    var to      = _config.To;
                    var from    = _config.To;
                    var subject = _config.Subject;

                    var emailModel = new ContactUsEmailModel
                                     (
                        _config.Subject,
                        model.Email,
                        model.FirstName,
                        model.LastName,
                        model.Message
                                     );

                    var body = await _razorRenderer.RenderViewToStringAsync("~/Views/Email/ContactUs.cshtml", emailModel);

                    await _emailService.SendHtmlAsync(to, from, subject, body);

                    model.SubmitSuccess = true;
                }
                catch (Exception ex)
                {
                    Log.LogError(ex, "There was an error sending an email: {ErrorMessage}", ex.Message);

                    model.SubmitSuccess = false;
                }
            }
        }
        else
        {
            LogValidationErrors();
        }

        return(View(model));
    }