public ActionResult AjaxSendEmail(ContactFormViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return PartialView("_ContactForm", vm);
            }

            var email = new EmailDetail
            {
                From = vm.Email,
                DisplayName = vm.FullName,
                Subject = vm.Subject,
                Body = vm.Message,
                IsBodyHtml = false
            };
            _mailer.Send(email);

            return Content(string.Format("<div class=\"alert alert-success\" role=\"alert\">{0}</div>", vm.ThankYouText), "text/html");
        }
Example #2
0
        public IActionResult Contact(ContactFormViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    //var user = await _userHelper.GetUserByEmailAsync(model.Username);
                    //var formContact = _context.ContactForms.FindAsync();
                    //if (formContact == null)
                    //{

                    //    formContact = new ContactForm
                    //    {
                    //        Name = model.Name,
                    //        Email = model.Email,
                    //        Message = model.Message,
                    //        Subject = model.Subject
                    //    };

                    //    var result = await _context.Add(formContact);
                    //    if (result != IdentityResult.Success)
                    //    {
                    //        this.ModelState.AddModelError(string.Empty, "* The user couldn't be created.");
                    //        return this.View(model);
                    //    }
                    //}

                    _mailHelper.SendMail("*****@*****.**", "Contact Form - YourVet App", $"<h1>YourVet - Contact from the App</h1>" +
                                         $"" +
                                         $"<br/>" +
                                         $"<p><strong>Contact Name:</strong> {model.Name}</p>" +
                                         $"<p><strong>Email:</strong> {model.Email}</p>" +
                                         $"<br/>" +
                                         $"<p><strong>Subject:</strong> {model.Subject}</p>" +
                                         $"<p><strong>Message:</strong> {model.Message}</p>" +
                                         $"<br/>" +
                                         $"_________________________________________________");

                    _mailHelper.SendMail(model.Email, "Contact Form - YourVet App", $"<h1>YourVet - Email received successfully</h1>" +
                                         $"<body>" +
                                         $"<br/>" +
                                         $"" +
                                         $"<h4>Welcome to YourVet, we confirm that we have received your email successfully.</h4>" +
                                         $"<br/>" +
                                         $"<p><strong>Contact Name:</strong> {model.Name}</p>" +
                                         $"<p><strong>Email:</strong> {model.Email}</p>" +
                                         $"<br/>" +
                                         $"<p><strong>Subject:</strong> {model.Subject}</p>" +
                                         $"<p><strong>Message:</strong> {model.Message}</p>" +
                                         $"<br/>" +
                                         $"<p>We will contact you as soon as possible.</p><body>");

                    ViewBag.Message = "We appreciate your contact, and we will reply as soon as possible!";
                }
                catch (Exception exe)
                {
                    ModelState.AddModelError(string.Empty, exe.Message);
                }
            }

            return(View("Index"));
        }
        public ActionResult RenderForm()
        {
            var viewModel = new ContactFormViewModel();

            return(PartialView("ContactForm", viewModel));
        }
        public async Task <IActionResult> Submit(ContactFormViewModel form, int?productId, int?pageId)
        {
            if (ModelState.IsValid)
            {
                var setting = repository.Setting;
                if (setting != null)
                {
                    var smtpClient = new SmtpClient {
                        Host                  = setting.Host, // set your SMTP server name here
                        Port                  = setting.Port, // Port
                        EnableSsl             = setting.EnableSsl,
                        DeliveryMethod        = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,// disable it
                        Credentials           = new NetworkCredential(setting.FromEmail, Misc.DecodeBase64(setting.Password))
                    };

                    StringBuilder body = new StringBuilder()
                                         .AppendLine("Hi,")
                                         .AppendLine()
                                         .AppendLine("A new enquiry has been submitted.");

                    if (!string.IsNullOrEmpty(form.ProductInterested))
                    {
                        body.AppendLine()
                        .AppendLine("------------------------------")
                        .AppendLine("Product Interested:")
                        .AppendFormat("{0} x {1}", form.ProductInterested, form.Qty)
                        .AppendLine()
                        .AppendLine("Ship To: " + form.ShipToName)
                        .AppendLine("Address: " + form.ShipToAddress)
                        .AppendLine("------------------------------");
                    }

                    body.AppendLine()
                    .AppendLine("Customer Name: " + form.Name)
                    .AppendLine("Company      : " + form.Company)
                    .AppendLine("Phone No.    : " + form.ContactNo)
                    .AppendLine("Email        : " + form.Email)
                    .AppendLine("Message      : " + form.Message)
                    .AppendLine()
                    .AppendLine();

                    using (var message = new MailMessage(setting.Email, setting.AdminEmail)
                    {
                        Subject = "New enquiry submitted!",
                        Body = body.ToString()
                    }) {
                        try {
                            await smtpClient.SendMailAsync(message);

                            return(RedirectToAction("Completed", "Cart"));
                        } catch (Exception ex) {
                            TempData["error"] = ex.Message;
                        }
                    }
                }
            }
            else
            {
                TempData["error"] = "The are something error in following fields: <br />";
                foreach (var modelState in ModelState.Values)
                {
                    foreach (var modelError in modelState.Errors)
                    {
                        TempData["error"] += " <li>" + modelError.ErrorMessage + " </li>";
                    }
                }
            }

            if (productId != null)
            {
                return(RedirectToAction("Index", "Product", new { Id = productId }));
            }
            if (pageId != null)
            {
                return(RedirectToAction("Index", "Page", new { Id = pageId }));
            }
            else
            {
                return(RedirectToAction("Error", "Error"));
            }
        }
        private MailMessage CreateSmtpMessage(string fromAddress, string toAddresses, ContactFormViewModel vm)
        {
            var emailSubject = "There has been a contact for submitted";
            var emailBody    = $"A new contact form has been received from {vm.Name}. Their comments were: {vm.Comment}";

            var smtpMessage = new MailMessage();

            smtpMessage.Subject = emailSubject;
            smtpMessage.Body    = emailBody;
            smtpMessage.From    = new MailAddress(fromAddress);
            smtpMessage.To.Add(toAddresses);

            return(smtpMessage);
        }
        public ActionResult RenderContactForm()
        {
            var vm = new ContactFormViewModel();

            return(PartialView("~/Views/Partials/ContactForm.cshtml", vm));
        }
Example #7
0
        public ActionResult Contact(ContactFormViewModel contact)
        {
            if (ModelState.IsValid)
            {
                //How to send email:
                //Construct a string value that will represent the
                //mail message.

                //SET DEFAULT VALUES
                contact.TimeStamp = DateTime.Now;
                //optionally you can hard code your subject (helps with
                //mail sorting)--Usually this is done when you OMIT the
                //subject field from the mail form

                string messageContent = $"Name: {contact.Name}<br />Email:" +
                                        $"{contact.Email}<br />Subject: {contact.Subject}<br />" +
                                        $"<h4>Message<h4> {contact.Message}<br />TimeStamp: {contact.TimeStamp}";

                //If you wanted them to see their subjec, you could change the order of operations
                //and move the hard code of the subject here(you would see their original subject as part
                //of the messageContent variable).


                //Create a Mail Message Object (System.Net.Mail)
                //From :                    //To:                   //subject:     //Body:
                MailMessage m = new MailMessage("*****@*****.**", "*****@*****.**", contact.Subject, messageContent);
                //allow for html body
                m.IsBodyHtml = true;
                //replyto set to reply to the original emailer, not your
                //website
                m.ReplyToList.Add(contact.Email); //Respond to the persons
                                                  //email that SENT you a message from your website.

                //CC/BCC
                //m.CC.Add(contact.Email);
                //Carbon Copy all recipients can see each other on the
                //email

                //BCC is added the same way, BCC is a blind carbon copy
                //Priority
                m.Priority = MailPriority.High; //optional setting
                                                //Smtp client
                SmtpClient client = new SmtpClient("mail.alexcroth.com");
                //assign client credentials
                client.Credentials = new NetworkCredential("*****@*****.**",
                                                           "Gibson89u@");


                //send the message
                using (client)
                {
                    try
                    {
                        client.Send(m);
                    }

                    catch
                    {
                        ViewBag.ErrorMessage = "There was an error sending your message. Please try again";
                        return(View(contact));
                    }
                }//Closes the connection on client

                //redirect to the confirmation
                return(View("ContactConfirm", contact));
            }
            //if it fails validation return to the form
            //sending the contact object back to the view
            //to repopulate the form.
            return(View(contact));
        }
 public ContactViewModel()
 {
     Form = new ContactFormViewModel();
 }
 public ContactViewModel()
 {
     Form = new ContactFormViewModel();
 }
Example #10
0
 public ActionResult Submit(ContactFormViewModel viewModel)
 {
     return(RedirectToCurrentUmbracoPage());
 }
Example #11
0
        public ActionResult HandleContactForm(ContactFormViewModel model)
        {
            //Check if hidden field was filled in
            if (!string.IsNullOrEmpty(model.Tip))
            {
                return(CurrentUmbracoPage());
            }

            //Check if captcha was good
            var  googleToken  = Request["g-recaptcha-response"];
            bool validCaptcha = ValidateCaptcha(googleToken);

            //Check if the dat posted is valid (All required's & email set in email field)
            if (!ModelState.IsValid)
            {
                //Not valid - so lets return the user back to the view with the data they entered still prepopulated
                return(CurrentUmbracoPage());
            }

            LogHelper.Info(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "validCaptcha is " + validCaptcha.ToString());
            if (!validCaptcha)
            {
                return(CurrentUmbracoPage());
            }

            using (SmtpClient smtpClient = new SmtpClient("127.0.0.1", 25))
            {
                smtpClient.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "M@1lerJ3113M@art3n");
                smtpClient.UseDefaultCredentials = false;
                smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtpClient.EnableSsl             = false;

                MailMessage email = new MailMessage
                {
                    Body       = "<p>from: " + model.Name + "</p>" + "<p>email: " + model.Email + "</p>" + "<p>Subject: " + model.Subject + "</p>" + "<p>Message: " + model.Message + "</p>",
                    IsBodyHtml = true,
                    Subject    = model.Subject != null ? model.Subject : "Contact request"
                };
                //Setting From , To and CC
                email.From = new MailAddress("*****@*****.**");
                email.To.Add(new MailAddress("*****@*****.**"));


                try
                {
                    //Try & send the email with the SMTP settings
                    LogHelper.Info(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "mail send is true");

                    smtpClient.Send(email);
                }
                catch (Exception ex)
                {
                    //Throw an exception if there is a problem sending the email
                    LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "mail send failed", ex);

                    throw ex;
                }
            }

            //Update success flag (in a TempData key)
            //TempData["IsSuccessful"] = true;

            //All done - lets redirect to the current page & show our thanks/success message
            return(RedirectToCurrentUmbracoPage());
        }
        public ActionResult HandleFormSubmit(ContactFormViewModel model)
        {
            if (ModelState.IsValid)
            {
                var sb = new StringBuilder();

                sb.AppendFormat("<p>Email from website: {0}</p>", model.Title);

                sb.AppendFormat("<p>FName: {0}</p>", model.FName);
                sb.AppendFormat("<p>LName: {0}</p>", model.LName);

                sb.AppendFormat("<p>Email: {0}</p>", model.Email);
                sb.AppendFormat("<p>Title: {0}</p>", model.Title);
                sb.AppendFormat("<p>Address1: {0}</p>", model.Address1);
                sb.AppendFormat("<p>Address2: {0}</p>", model.Address2);
                sb.AppendFormat("<p>City: {0}</p>", model.City);
                sb.AppendFormat("<p>Origin: {0}</p>", model.Origin);
                sb.AppendFormat("<p>Zip: {0}</p>", model.Zip);


                sb.AppendFormat("<p>Phone: {0}</p>", model.Phone);

                sb.AppendFormat("<p>Comments: {0}</p>", model.Comments);

                SmtpClient smtp = new SmtpClient();
                smtp.EnableSsl             = true;
                smtp.Host                  = ConfigurationManager.AppSettings["SmtpHost"];
                smtp.Port                  = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
                smtp.UseDefaultCredentials = false;
                smtp.Credentials           = new NetworkCredential(
                    ConfigurationManager.AppSettings["SmtpCredentialsUid"],
                    ConfigurationManager.AppSettings["SmtpCredentialsPwd"]);


                MailMessage message = new MailMessage();

                message.Subject = "Inquiry";

                message.From = new MailAddress(
                    ConfigurationManager.AppSettings["From"]);


                string toAddress = ConfigurationManager.AppSettings["To"];
                if (toAddress.Contains(","))
                {
                    message.To.Add(toAddress); //multiple address found
                }
                else
                {
                    message.To.Add(new MailAddress(toAddress)); //only one address found
                }
                message.Sender     = new MailAddress(ConfigurationManager.AppSettings["From"]);
                message.Body       = sb.ToString();
                message.IsBodyHtml = true;

                try
                {
                    smtp.Send(message);
                }
                catch (SmtpException smtpEx)
                {
                    // Log or manage your error here, then...
                    return(RedirectToUmbracoPage(1063)); // <- My published error page.
                }

                TempData["success"] = true;
                return(CurrentUmbracoPage());
            }
            else
            {
                return(CurrentUmbracoPage());
            }
        }
        //
        // GET: /ContactFormSurface/

        public ActionResult Index()
        {
            var model = new ContactFormViewModel();

            return(PartialView("ContactForm", model));
        }
 public IActionResult Kaydet(ContactFormViewModel viewModel)
 {
     return(View("Contact", viewModel));
 }
Example #15
0
        public ActionResult SendContactForm(ContactFormViewModel model)
        {
            var page = (CurrentPage);// as ContactFormDocType);

            if (ModelState.IsValid)
            {
                var emailClient = new SmtpClient();
                var message     = new MailMessage();
                ViewData.Model = model;
                string messageBody;
                using (var sw = new StringWriter())
                {
                    var viewResult  = ViewEngines.Engines.FindPartialView(ControllerContext, ConfigurationManager.AppSettings["ContactFormMailTemplate"]);
                    var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                    viewResult.View.Render(viewContext, sw);
                    messageBody = sw.GetStringBuilder().ToString();
                }
                message.Body       = messageBody;
                message.IsBodyHtml = true;
                message.Subject    = string.Format(ConfigurationManager.AppSettings["ContactFormSubjectMask"], model.Subject);
                var emailAddresses = ConfigurationManager.AppSettings["ContactFormReceiver"].ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var addr in emailAddresses)
                {
                    message.To.Add(new MailAddress(addr));
                }

                var bccEmailAddresses = ConfigurationManager.AppSettings["ContactFormReceiverBcc"].ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var addr in bccEmailAddresses)
                {
                    message.Bcc.Add(new MailAddress(addr));
                }
                emailClient.Send(message);
                if (page != null)
                {
                    return(Redirect(page.Url + "?success"));
                }
            }
            var index = ModelState.Keys.ToList().IndexOf("ReCaptcha");

            if (index > 0)
            {
                var captchaMessages = new List <string>();
                var values          = ModelState.Values.ToList();

                foreach (var error in values[index].Errors)
                {
                    var translatedMessage = Umbraco.GetDictionaryValue(error.ErrorMessage);
                    captchaMessages.Add(!string.IsNullOrEmpty(translatedMessage) ? translatedMessage : error.ErrorMessage);
                }

                if (captchaMessages.Any())
                {
                    ModelState["ReCaptcha"].Errors.Clear();
                    foreach (var msg in captchaMessages)
                    {
                        ModelState["ReCaptcha"].Errors.Add(msg);
                    }
                }
            }
            return(CurrentUmbracoPage());
        }
Example #16
0
        public IActionResult Contact()
        {
            var model = new ContactFormViewModel();

            return(View());
        }
        public ActionResult ContactUs(ContactFormViewModel model)
        {
            try
            {
                // This code will create a Document of type Contact Submission and add it to the Contact Us Submissions list in the Umbraco Back end
                // This is done in case there are any issues with the emailer.
                // Get Submissions List Node ID
                var submissionsNodeId = Umbraco.TypedContentAtRoot().First(_ => _.Name == "Contact Us Submissions").Id;
                // Create a new ContactSubmission document and title it the users name
                IContent doc = ApplicationContext.Services.ContentService.CreateContent(model.FirstName + " " + model.LastName, submissionsNodeId, "ContactSubmission");
                // Populate all the data
                doc.Properties["messageTopic"].Value = model.MessageType;
                doc.Properties["firstName"].Value = model.FirstName;
                doc.Properties["lastName"].Value = model.LastName;
                doc.Properties["email"].Value = model.Email;
                doc.Properties["phoneNumber"].Value = model.PhoneNumber;
                doc.Properties["message"].Value = model.Message;
                // If this is a logged in user
                if (User.Identity.IsAuthenticated) doc.Properties["memberId"].Value = model.MemberId;
                // Save (but do not publish) the contact submision
                ApplicationContext.Services.ContentService.Save(doc);

                string mailData = CurrentPage.GetPropertyValue<string>("categoriesAndEmails");
                IDictionary<string, IEnumerable<string>> categoriesAndEmails = ContactFormViewModel.GetCategoriesAndEmails(mailData);
                IEnumerable<string> emails = categoriesAndEmails[model.MessageType];

                const string na = "N/A";
                // Build a dictionary for all the dynamic text in the email template
                var dynamicText = new Dictionary<string, string>
                    {
                        {"<%MemberId%>", model.MemberId ?? na},
                        {"<%FirstName%>", model.FirstName},
                        {"<%LastName%>", model.LastName},
                        {"<%YNumber%>", model.YNumber ?? na},
                        {"<%Username%>", model.Username ?? na},
                        {"<%Email%>", model.Email},
                        {"<%Phone%>", model.PhoneNumber},
                        {"<%MessageBody%>", model.Message}
                    };
                // Get the Umbraco root node to access dynamic information (phone numbers, emails, ect)
                IPublishedContent root = Umbraco.TypedContentAtRoot().First();

                //Get the Contact Us Email Template ID
                object emailTemplateId = null;
                string smtpEmail = null;
                string template = CurrentPage.GetPropertyValue<string>("emailTemplate");
                if (template == "Member")
                {
                    emailTemplateId = root.GetProperty("memberContactUsTemplate").Value;
                    smtpEmail = root.GetProperty("smtpEmailAddress").Value.ToString();
                }
                if (template == "Provider")
                {
                    emailTemplateId = root.GetProperty("providerContactUsTemplate").Value;
                    smtpEmail = root.GetProperty("providerSmtpEmailAddress").Value.ToString();
                }
                if (template == "Broker")
                {
                    emailTemplateId = root.GetProperty("brokerContactUsTemplate").Value;
                    smtpEmail = root.GetProperty("brokerSmtpEmailAddress").Value.ToString();
                }

                foreach (string email in emails)
                {
                    try
                    {
                        SendEmail(email, model.MessageType, BuildEmail((int)emailTemplateId, dynamicText), smtpEmail);
                    }
                    catch (Exception ex)
                    {
                        // Create an error message with sufficient info to contact the user
                        string additionalInfo = model.FirstName + " " + model.LastName + " could not send a contact us email request. Please contact at " + model.Email;
                        // Add the error message to the log4net output
                        log4net.GlobalContext.Properties["additionalInfo"] = additionalInfo;
                        // Log the error
                        logger.Error("Unable to complete Contact Us submission due to SMTP error", ex);
                        logger.Error("Template: " + (template != null ? template : "error") + " - " + "templateID: " + (emailTemplateId != null ? emailTemplateId.ToString() : "error") + " : " + (smtpEmail != null ? smtpEmail : "error"));
                        // Set the sucess flag to true and post back to the same page
                        TempData["IsSuccessful"] = false;
                        return RedirectToCurrentUmbracoPage();
                    }
                }

                // Set the sucess flag to true and post back to the same page
                TempData["IsSuccessful"] = true;
                return RedirectToCurrentUmbracoPage();
            }
            catch (Exception ex) // If the message failed to send
            {
                // Create an error message with sufficient info to contact the user
                string additionalInfo = model.FirstName + " " + model.LastName + " could not send a contact us email request. Please contact at " + model.Email;
                // Add the error message to the log4net output
                log4net.GlobalContext.Properties["additionalInfo"] = additionalInfo;
                // Log the error
                logger.Error("Unable to complete Contact Us submission", ex);
                // Set the success flag to false and post back to the same page
                TempData["IsSuccessful"] = false;
                return RedirectToCurrentUmbracoPage();
            }
        }
        public ViewResult New()
        {
            var viewModel = new ContactFormViewModel();

            return(View("ContactForm", viewModel));
        }